我已經使用express編寫了簡單的PUT服務。現在當我打電話給PUT服務並傳遞數據時,我發現了一些奇怪的東西。當我使用req.data讀取數據時,我可以看到我傳遞的數據。但是當我嘗試進入req.data的屬性時,我得到一個未定義的。Express無法讀取PUT請求中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;
};
這裏是飛行
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;
}
任何想法爲什麼會發生這種情況?
'飛行'是同步功能嗎? – Nonemoticoner
是的。我已更新了問題 – Yameen