0

我正在学习

这是代码。它运作良好。

但是,我不明白为什么我不能直接使用 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,
    comments:[],
  },
  'learn-js':{
    upvotes:0,
    comments:[],
  },
}

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"));
4

1 回答 1

1

你不能使用的原因:

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

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

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

在这里,您现在有了键/值对。

另一个工作的原因是因为ES2015 速记属性

于 2020-10-20T11:48:47.263 回答