I am learning 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?
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