0

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"));
Leo Li
  • 15
  • 5
  • Because `{req.body.username,req.body.text}` is invalid syntax. `{username: req.body.username, text: req.body.text}` would be valid… So probably, `.push(req.body)` would do… – deceze Oct 20 '20 at 11:43
  • Thanks for your answer, I got it now. – Leo Li Oct 20 '20 at 12:00

1 Answers1

1

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

yeeeehaw
  • 191
  • 2
  • 5