nodejs request.body返回空对象{}

时间:2016-10-18 17:32:42

标签: node.js express body-parser

我正在使用以下代码,request.body返回{}我希望我的输出为{username:"Mani",password:"pass"},请帮我修复此代码示例中是否有任何错误。

app.js

var bodyParser = require('body-parser');
var express = require('express');
var app = express();

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

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
  response.send(request.body);    // echo the result back
});

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

npm版本:

表达4.14.0

body-parser 1.15.2

url http://localhost:3000/

方法:POST

header:Content-Type:application / json

请求有效负载:{username:“Mani”,密码:“pass”}

app.js控制台的输出是{}

2 个答案:

答案 0 :(得分:0)

看来你的身体是一个json文件。您需要配置body-parser来接受json:

app.use(bodyParser.json());

答案 1 :(得分:0)

试试这个,"内容类型":" application / x-www-form-urlencoded",必须使用此

 // chnage content-type to content-type": "application/x-www-form-urlencoded 

 var settings = {
 "async": true,
 "crossDomain": true,
 "url": "http://localhost:3000/",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
 },
"data": {
"name": "mane"
} 
 }

 $.ajax(settings).done(function (response) {
 console.log(response);
 });