无法使用 NodeJS/ExpressJS 和 Postman 获取 POST 数据 [英] Can't get POST data using NodeJS/ExpressJS and Postman

查看:17
本文介绍了无法使用 NodeJS/ExpressJS 和 Postman 获取 POST 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我服务器的代码:

var express = require('express');var bodyParser = require("body-parser");var app = express();app.use(bodyParser.json());app.post("/", function(req, res) {res.send(req.body);});app.listen(3000, function () {console.log('监听 3000 端口的示例应用程序!');});

从 Postman,我向

解决方案

添加请求的编码.这是一个例子

<代码>..app.use(bodyParser.json());app.use(bodyParser.urlencoded({extended: true }));..

然后在 Postman 中选择 x-www-form-urlencoded 或者将 Content-Type 设置为 application/json 并选择 raw

编辑以使用 raw

原始

<代码>{富":酒吧"}

标题

内容类型:application/json

EDIT #2回答聊天中的问题:

  1. 为什么它不能与表单数据一起使用?

你当然可以,看看这个答案How to handle FormData from express4

  1. 使用 x-www-form-urlencodedraw
  2. 有什么区别

application/json 和 application/x 的区别-www-form-urlencoded

This is the code of my server :

var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());

app.post("/", function(req, res) {
    res.send(req.body);
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

From Postman, I launch a POST request to http://localhost:3000/ and in Body/form-data I have a key "foo" and value "bar".

However I keep getting an empty object in the response. The req.body property is always empty.

Did I miss something?

解决方案

Add the encoding of the request. Here is an example

..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
..

Then select x-www-form-urlencoded in Postman or set Content-Type to application/json and select raw

Edit for use of raw

Raw

{
  "foo": "bar"
}

Headers

Content-Type: application/json

EDIT #2 Answering questions from chat:

  1. why it can't work with form-data?

You sure can, just look at this answer How to handle FormData from express 4

  1. What is the difference between using x-www-form-urlencoded and raw

differences in application/json and application/x-www-form-urlencoded

这篇关于无法使用 NodeJS/ExpressJS 和 Postman 获取 POST 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆