[英]Why I can't use req.body as parameter directly?
I am learning node.js .我正在学习node.js 。
Here is the code.这是代码。 It works well.
它运作良好。
However, I don't understand why I can't use req.body as a parameter directly?但是,我不明白为什么我不能直接使用 req.body 作为参数?
articlesInfo[articleName].comments.push({req.body.username,req.body.text});
Thanks.谢谢。
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"));
the reason why you can't use :你不能使用的原因:
articlesInfo[articleName].comments.push({req.body.username,req.body.text});
is because it's a syntax error, you're creating an object without any keys, you're only setting the values.是因为这是一个语法错误,您正在创建一个没有任何键的对象,您只是在设置值。
articlesInfo[articleName].comments.push({username: req.body.username, text: req.body.text});
Here you now have key/value pairs.在这里,您现在拥有键/值对。
The reason why the other one is working is because because of ES2015 shorthand properties另一个工作的原因是因为ES2015 速记属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.