简体   繁体   中英

Why I can't use req.body as parameter directly?

I am learning .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM