Express无法读取PUT请求中req.data的属性值

我用express写了一个简单的PUT服务。 现在,当我打电话给PUT服务,并通过它的数据,我发现一些奇怪的东西。 当我使用req.data读取数据时,我可以看到我传递的数据。 但是当我尝试进入req.data的属性,我得到一个未定义的。

这是我的app.js

module.exports = function (data) { var express = require('express'); var path = require('path'); var routes = require('./routes/index')(data); var bodyParser = require('body-parser'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static(path.join(__dirname, 'public'))); app.use(function (req, res, next) { res.set('X-Powered-By', 'Flight Tracker'); next(); }); //CORS middleware app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:63018'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); app.put('/newflight', routes.create); return app; }; 

这是航class

 var Flight = function () { this.data = { number: null, origin: null, destination: null, departs: null, arrives: null, actualDepart: null, actualArrive: null }; this.fill = function (info) { for (var prop in this.data) { if (this.data[prop] !== 'undefined') { this.data[prop] = info[prop]; } } }; this.triggerDepart = function () { this.data.actualDepart = Date.now(); }; this.triggerArrive = function () { this.data.actualArrive = Date.now(); }; this.getInfo = function () { return this.data; }; }; //Serving as factory to create instances of Objects module.exports = function (info) { var instance = new Flight(); instance.fill(info); return instance; } 

这是我的路线

 module.exports = function (data) { var flight = require('../flight'); for (var number in data) { console.log(data[number]); data[number] = flight(data[number]); }; var functions = {}; functions.create = function(req,res){ if(!req.body) { return res.sendStatus(400); } else{ console.log(req.body); console.log(req.body.number); console.log(req.body.origin); console.log(req.body.destination); var number = req.body.number; data[number] = flight(req.body); console.log(data[number]); res.json({ status:202, statusText:"Entries have been created", data:data }); } }; return functions; } 

我也有从上面的创build方法的输出: 在这里输入图像描述

任何想法为什么发生这种情况?

Solutions Collecting From Web of "Express无法读取PUT请求中req.data的属性值"

基本上我的postdata是不正确的。 我传递postdata.data时,我应该只传递postdata。 这解决了这个问题。 另外,我在头文件中添加了'Content-Type':'application / json'。