简体   繁体   English

Node.js请求主体为空

[英]Node.js req.body empty

I am having a hell of a time with this one. 我在这玩的很开心。 I don't know why my node.js response is empty. 我不知道为什么我的node.js响应为空。 It comes back {} if I send it through the javascript here, or if I use the Advanced REST client. 如果我通过此处的javascript发送,或者使用Advanced REST客户端,它将返回{}。 Here is my code: 这是我的代码:

client.js client.js

unction ajaxPost(){

var req = new XMLHttpRequest();
var payload = {'Add Item':'Add Item',
                'name':document.getElementById('submitForm').elements[0].value,
                'reps':document.getElementById('submitForm').elements[1].value,
                'weight':document.getElementById('submitForm').elements[2].value,
                'date':document.getElementById('submitForm').elements[3].value,
                'lbs':document.getElementById('submitForm').elements[4].value
           }
payload['test'] = 'value!';
console.log('did this happen?');
console.log(payload['test']);
var url = '/edit';
req.open('POST', url, true);
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load',function(){
  if(req.status >= 200 && req.status < 400){
    var response = JSON.parse(req.responseText);
    console.log('you got a response!')

  } else {
    console.log("Error in network request: " + req.statusText);
  }});
console.log(JSON.stringify(payload));
req.send(JSON.stringify(payload));

event.preventDefault();

}

HTML 的HTML

<form id = "submitForm">
    <input type="text" name="name" id="name" value='test'>Name<br>
    <input type="text" name="reps" id="reps" value='10'>Reps<br>
    <input type="text" name="weight" id="weight" value='100'>Weight<br>
    <input type="text" name="date" id="date" value='1/1/16'>Date<br>
    <input type="text" name="lbs" id="lbs" value='1'>Pounds<br>
    <input type="submit" onclick = 'ajaxPost()' value="Add Item">
</form>

server 服务器

var express = require('express');
var mysql = require('./dbcon.js');
var bodyParser = require('body-parser');

var app = express();
var handlebars = require('express-handlebars').create({defaultLayout:'main2'});

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', 3010);

app.post('/edit',function(req,res,next){
  //var context = {};
  console.log('you posted!');
  console.log(req.body);

In my console, I see that the req.body is {}. 在我的控制台中,我看到req.body是{}。

I don't know what I am doing wrong. 我不知道我在做什么错。 I have tried using httpbin and I can see that the javascript works fine, which means I am probably doing something wrong on the node side, but I cannot figure out what. 我尝试使用httpbin进行尝试,可以看到javascript正常工作,这意味着我可能在节点端做错了事,但是我无法弄清楚是什么。 If I instead use method="submit" on the form, then the post goes through just fine, but it's not what I want to do. 如果我改为在表单上使用method =“ submit”,则该帖子可以正常运行,但这不是我想要的。 What am I doing wrong?? 我究竟做错了什么?? Because advanced REST client also fails, I am guessing it is node? 因为高级REST客户端也会失败,所以我猜它是节点吗?

You are sending json in the request, but you only have middleware setup to handle url encoded requests. 您正在请求中发送json,但只有中间件设置可以处理url编码的请求。 Add this to your middleware and json requests should populate in the req.body. 将此添加到您的中间件中,并且json请求应填充在req.body中。

app.use(bodyParser.json());

More info can be found at in the body parser documentation . 可以在主体解析器文档中找到更多信息。 Specifically you'll notice that the middleware you are using urlencoded states that it only parses urlencoded bodies (this is where Content-Type is used). 具体来说,您会注意到您使用的是 urlencoded中间件状态是它仅解析urlencoded的主体(这是使用Content-Type的地方)。

You are setting the header to be json 您正在将标头设置为json

req.setRequestHeader('Content-Type', 'application/json');

and not using bodyParser.json() . 而不使用bodyParser.json()

Try adding app.use(bodyParser.json()); 尝试添加app.use(bodyParser.json());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM