在postjs中,Req.body在post和put请求中为空

时间:2016-02-21 19:20:43

标签: node.js express body-parser

服务器文件是

'use strict';

var express        = require('express');
var compression    = require('compression');
var configDB       = require('./config/database');
var mongoose       = require("mongoose");
var bodyParser     = require('body-parser');
var logger         = require('morgan');
var path           = require('path');
var app            = express();

var deliveries     = require('./routes/deliveries');

var mongoString;
if (process.env.MONGOLAB_URI) {
 console.log('Now in HEROKU');
 mongoString = process.env.MONGOLAB_URI;
} else {
 mongoString = configDB.dev;
 console.log('In dev mongo', mongoString);
}

mongoose.connect(mongoString);
mongoose.connection;

app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
 extended: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api/deliveries', deliveries);

var server = app.listen(3000, function() {
 var host = 'localhost';
 var port = server.address().port;
 console.log('Listening at http://%s:%s', host, port);
});

module.exports = app;

我不知道服务器设置有什么问题。 发帖和提出请求一直很痛苦。 过去1小时我一直在与此作斗争。对我做错的任何帮助。

路线文件是

router.put('/cancel/:id', function(req, res) {
 deliveries.cancel(req, res);
});

deliveriesControllerActions.cancelDelivery = function(req, res) {
  console.log(req.headers['content-type']);
  if (!(util.isEmpty(req.query))) {
   req.body = req.query;
  }

 var deliveryid = req.params.deliveryid;
 var userid = req.body.userid;
 var cancelStatus = {
  status: true,
  timestamp: Date.now()
 };

if (!util.verifyInputFields(userid, deliveryid)) {
  util.sendErrResponse(res, 404, 'userid is empty');
} else {
 Delivery.findById(deliveryid)
   .exec(function(err, deliveryObject) {
    if (deliveryObject) {
      if (deliveryObject.cancelled_by_sender.status || deliveryObject.cancelled_by_admin.status || deliveryObject.cancelled_by_receiver.status) {
        saveUpdatedDelivery(res, userid, deliveryObject);
      } else {
        deliveryObject.status = deliveryRequestCancelledStatus;
        deliveryObject.cancelled_by_admin = cancelStatus;
        saveUpdatedDelivery(res, userid, deliveryObject);
      }
    } else if (err) {
      util.sendErrResponse(res, 404, err);
    }
  });
 }

}

1 个答案:

答案 0 :(得分:1)

问题是您没有向服务器发送适当类型的数据。您提交的内容不仅仅是application/jsonapplication/x-www-form-urlencodedtext/plain显而易见)。数据本身(和Content-Type)不正确,或者需要正确设置Content-Type标头。