我一直在使用Express和body-parser讀取應用程序的Angular端發送的JSON對象時遇到了相當多的麻煩。根據我所嘗試的,似乎我的變量賦值語法在某種程度上是不可靠的。到目前爲止,我已經嘗試了很多不同的語法,所以我希望有人能夠幫助我找出正確的方法,將請求主體中的各個位分配到相關的變量中。Express:將req.body對象中的數組分配給各個變量
下面是一些我迄今所做的故障排除:
驗證了對象,我要發送的數據實際上是被公佈。
驗證Content-Type是「application/json」。
已驗證body-parser正在處理請求,並且req.body中填充了數據。
嘗試使用和不使用「application/json」的顯式設置作爲內容類型,而不改變結果。
下面是如何$ HTTP是在發送對事物的角度側的數據:
.controller ('Ctrl', function($scope, $http) {
$scope.generateLabel = function(){
var httpData = [
{"addressToName": $scope.addressToName},
{"addressToStreet1": $scope.addressToStreet1},
{"addressToCity": $scope.addressToCity},
{"addressToState": $scope.addressToState},
{"addressToZip": $scope.addressToZip},
{"addressToEmail": $scope.addressToEmail},
{"parcelType": $scope.parcelType},
{"note": $scope.note},
{"sku": $scope.sku}];
$http({
method: 'POST',
url: '/postURL',
headers: {
'Content-Type': "application/json"
},
data: httpData
});
};
...這是我的郵政快遞航線的相關位:
var bodyParser = require('body-parser');
app.use(bodyParser.json({strict: false}));
app.post('/postURL', function(req, res) {
var addressToName = req.body.addressToName;
var addressToStreet1 = req.body.addressToStreet1;
var addressToCity = req.body.addressToCity;
var addressToState = req.body.addressToState;
var addressToZip = req.body.addressToZip;
var addressToCountry = 'US';
var addressToEmail = req.body.addressToEmail;
}
下面是我在測試節點控制檯時看到的內容。頂部的消息是從身體解析器的調試模式,那麼它的原始req.body,則變量我試圖將它們分配給:
body-parser:json content-type "application/json" +0ms
body-parser:json content-encoding "identity" +2ms
body-parser:json read body +1ms
body-parser:json parse body +13ms
body-parser:json parse json +1ms
Request body follows:
[ { addressToName: 'My name' },
{ addressToStreet1: 'My address' },
{ addressToCity: 'Anytown' },
{ addressToState: 'OR' },
{ addressToZip: '97504' },
{ addressToEmail: '[email protected]' },
{ parcelType: '8lb Box' },
{ note: '12314' },
{ sku: '11111' } ]
Variables assigned:
{ addressToName: undefined,
addressToStreet1: undefined,
addressToCity: undefined,
addressToState: undefined,
addressToZip: undefined,
addressToCountry: 'US',
addressToEmail: undefined }
在您的快遞POST路線中,您是否應該使用'req.body [0]'?看起來你得到它作爲長度爲1而不是一個原始對象的數組... –