【问题标题】:req.body is returning empty data, how to fix that?req.body 返回空数据,如何解决?
【发布时间】:2021-08-17 01:01:48
【问题描述】:

我正在尝试从我的应用程序测试 POST rest api。

我的 package.json 文件:

{
  "name": "crypto_backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "joi": "^17.4.0",
    "mongoose": "^5.12.12"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

我的 index.js 文件:

const express = require("express");

const app = express();

app.use(express.json());

const courses = [
  { id: 1, name: "uday1" },
  { id: 2, name: "uday2" },
  { id: 3, name: "uday3" },
  { id: 4, name: "uday4" },
];

app.get("/api/courseslist", (req, res) => {
  res.send(courses);
});

app.post("/api/courses", (req, res) => {

    console.log(req.body);

  const course = {
    id: courses.length + 1,
    name: req.body.name,
  };
  courses.push(course);
  res.send(course);
});

app.listen(3000, () => console.log("listening"));

当我使用 postman chrome 插件和 vscode rest 客户端扩展请求 POST 时,req.get 没有获取任何参数并且名称字段被视为空。

但我通过了如下请求。

POST http:/localhost:3000/api/courses

{
    "name": "sample"
}

在邮递员插件中选择原始数据并传递上述数据。

【问题讨论】:

  • 你能确认 post 端点被命中了吗?你在请求中设置了Content-Type 标头吗?
  • 发布请求被命中,并且在列表中也创建了一个条目,但没有参数。我正在创建 id 和 name 字段。 id 是自动创建的,名称作为参数传递,在那里它显示为空。即使我保留了console.log(req.body),它也是空括号{}。

标签: node.js json express req


【解决方案1】:

除了express.json,还需要加上express.urlencoded来解析body:

const express = require("express");

const app = express();

app.use(express.json());
app.use(express.urlencoded({extended:false}));

...

express.urlencoded() 函数是 Express 中内置的中间件函数。它使用 urlencoded 有效负载解析传入的请求,并使我们能够获取req.body

如果您想从表单而不是 Postman 获取数据,则不需要设置任何标题,因为当用户提交表单时,浏览器会为您发送所有必要的标题。所以,像这样一个简单的传统形式应该可以工作:

<form action="/api/courses" method="post">
  <input type="text" name="name" />
</form>

【讨论】:

  • 这似乎是邮递员的问题,它没有设置标题,在我将 application/json 保留为 Content-Type 之后,它正在工作。我还发布了一个问题,我从 ejs 模板表单传递相同的请求。表单中这些东西怎么设置?
  • 我添加更多信息。希望对你有帮助。
  • 是的,我尝试了真假。你能检查一下这个问题吗? stackoverflow.com/questions/67741580/…
猜你喜欢
  • 2020-03-05
  • 2017-08-30
  • 2022-01-11
  • 2014-01-28
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 2022-07-08
  • 1970-01-01
相关资源
最近更新 更多