【问题标题】:Why I can't use req.body as parameter directly?为什么我不能直接使用 req.body 作为参数?
【发布时间】:2021-02-03 05:31:06
【问题描述】:

我正在学习

这里是代码。效果很好。

但是不明白为什么不能直接使用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"));

【问题讨论】:

  • 因为{req.body.username,req.body.text} 是无效的语法。 {username: req.body.username, text: req.body.text} 是有效的......所以.push(req.body) 可能会......
  • 感谢您的回答,我知道了。

标签: node.js node.js express post push req


【解决方案1】:

不能使用的原因:

articlesInfo[articleName].comments.push({req.body.username,req.body.text});

是因为它是一个语法错误,你正在创建一个没有任何键的对象,你只是在设置值。

articlesInfo[articleName].comments.push({username: req.body.username, text: req.body.text});

您现在有键/值对。

另一个工作的原因是因为ES2015 shorthand properties

【讨论】:

  • 非常感谢。我现在明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2014-11-25
  • 1970-01-01
  • 2020-01-26
相关资源
最近更新 更多