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

查看:516
本文介绍了无法使用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上监听!’);
});

从邮递员,我向

解决方案

添加请求的编码。这是一个示例

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

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



编辑以使用原始



原始

  {
foo: bar
}

标题

 内容-类型:application / json 

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


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

您当然可以,只需查看此答案如何处理Express 4中的FormData


  1. 使用 x-www-form-urlencoded raw
  2. $ b $有什么区别b

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天全站免登陆