weixin_33670713 2016-03-11 19:33 采纳率: 0%
浏览 54

Node.js请求主体为空

I am having a hell of a time with this one. I don't know why my node.js response is empty. It comes back {} if I send it through the javascript here, or if I use the Advanced REST client. Here is my code:

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

<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 {}.

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. 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. What am I doing wrong?? Because advanced REST client also fails, I am guessing it is node?

  • 写回答

2条回答 默认 最新

  • ~Onlooker 2016-03-11 19:41
    关注

    You are sending json in the request, but you only have middleware setup to handle url encoded requests. Add this to your middleware and json requests should populate in the 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).

    评论

报告相同问题?

悬赏问题

  • ¥60 如何批量获取json的url
  • ¥15 对法兰连接元件所承受的表面载荷等效转化为法兰开孔接触面上的等效表面载荷?
  • ¥15 comsol仿真压阻传感器
  • ¥15 Python线性规划函数optimize.linprog求解为整数
  • ¥15 llama3中文版微调
  • ¥15 pg数据库导入数据序列重复
  • ¥15 三分类机器学习模型可视化分析
  • ¥15 本地测试网站127.0.0.1 已拒绝连接,如何解决?(标签-ubuntu)
  • ¥50 Qt在release捕获异常并跟踪堆栈(有Demo,跑一下环境再回答)
  • ¥30 python,LLM 文本提炼