为什么我不能直接使用 req.body 作为参数?
Why I can't use req.body as parameter directly?
我正在学习node.js。
这是代码。效果很好。
但是我不明白为什么不能直接使用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"));
无法使用的原因:
articlesInfo[articleName].comments.push({req.body.username,req.body.text});
是因为这是一个语法错误,您正在创建一个没有任何键的对象,您只是在设置值。
articlesInfo[articleName].comments.push({username: req.body.username, text: req.body.text});
这里你现在有 key/value 对。
另一个之所以起作用是因为ES2015 shorthand properties
我正在学习node.js。
这是代码。效果很好。
但是我不明白为什么不能直接使用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"));
无法使用的原因:
articlesInfo[articleName].comments.push({req.body.username,req.body.text});
是因为这是一个语法错误,您正在创建一个没有任何键的对象,您只是在设置值。
articlesInfo[articleName].comments.push({username: req.body.username, text: req.body.text});
这里你现在有 key/value 对。
另一个之所以起作用是因为ES2015 shorthand properties