为什么我不能直接使用req.body作为参数?

问题描述

我正在学习

这是代码效果很好。

但是,我不明白为什么我不能直接使用req.body作为参数?

articlesInfo[articleName].comments.push({req.body.username,req.body.text});

谢谢。

import express from 'express';
import bodyParser from 'body-parser';

const articlesInfo ={
  'learn-react':{
    upVotes:0,comments:[],},'learn-node':{
    upVotes:0,'learn-js':{
    upVotes:0,}

const app = express();

app.use(bodyParser.json());

app.post('/api/articles/:name/add-comment',(req,res)=>{
  const {username,text} = req.body;
  const articleName = req.params.name;
  articlesInfo[articleName].comments.push({username,text});
  res.status(200).send(articlesInfo[articleName]);
});

app.listen(8000,()=>console.log("Listening on port 8000"));

解决方法

不能使用的原因:

articlesInfo[articleName].comments.push({req.body.username,req.body.text});

是因为这是一种语法错误,您创建的对象没有任何键,只设置了值。

articlesInfo[articleName].comments.push({username: req.body.username,text: req.body.text});

现在您有了键/值对。

另一个工作的原因是因为ES2015 shorthand properties