2017-06-13 30 views
1

Sample 'Advanced REST Client' Requestreq.body未顯示爲鍵值對的一個,但req.headers和其他人做我使用郵差和高級REST客戶端創建下面的代碼基本POST請求

-

'use strict'; 
var express = require('express'); 
var bodyParser = require('body-parser'); 
var app = express(); 
var http = require('http'); 

// configure the app to use bodyParser() 
app.use(bodyParser.urlencoded({ 
    extended: false 
})); 
app.use(bodyParser.json()); 
//app.listen(6666); 

http.createServer(function (req, res) { 
    h2s(req, res); 
}).listen(6666, '127.0.0.1'); 

console.log('Server running at http://127.0.0.1:6666/'); 

module.exports = function h2s(req, res) { 
    console.log("inside h2s"); 
    app.use(function (req, res) { 
     console.log("req.body : " + req.body); 
     res.send("OK"); 
    }); 
} 

但是,當我調試時,我發現req.body在「req對象樹」中缺少。更奇怪的是,我對req.headers所做的所有更改都可以在req對象樹中找到。

看起來我似乎在犯一個微不足道的錯誤,但我無法弄清楚。經過一個小時左右的解決方案,但沒有運氣!

有沒有人可以弄清楚爲什麼req.body似乎從req對象樹中缺少?

對我有很大的幫助。謝謝!

+0

的內容是什麼類型的申請,並就共同頭的細節。 –

+0

感謝您的回覆,Manish。我附上了一張我在ARC發佈的請求的照片。 Content-Type是application/json。 – Sandy

+0

你可以添加代碼來執行你試圖解析的任何數據嗎? – CruelEngine

回答

0

它看起來像你必須在你的代碼的幾個問題:的

代替

http.createServer(function (req, res) { 
    h2s(req, res); 
}).listen(6666, '127.0.0.1'); 

console.log('Server running at http://127.0.0.1:6666/'); 

module.exports = function h2s(req, res) { 
    console.log("inside h2s"); 
    app.use(function (req, res) { 
    console.log("req.body : " + req.body); 
    res.send("OK"); 
    }); 
} 

對於創建服務器,嘗試

http.createServer(app).listen(8000, '127.0.0.1'); //using http 

或(直接使用快遞)

app.listen(8000,function(){ 
    console.log('Server running at http://127.0.0.1:8000/'); 
}); 

然後註冊一個處理函數爲您的要求,也可以訪問req.body

app.use(function (req, res) { 
    console.log("req.body : " + req.body); 
    res.send("OK"); 
}); 
+0

謝謝!這有助於獲得200 OK的迴應。此外,我如何將它添加到一個函數?我想在功能下將它們分開。 – Sandy

+0

@Sandy您希望在單獨的功能中執行哪個部分?代碼中沒有太多的功能,你只需創建一個服務器,然後註冊一個處理函數來處理你的請求。 當然,如果你想要的話,你可以命名該函數,像 函數reqHandler(req,res)console.log(「req.body:」+ req.body); res.send(「OK」); } 並註冊它像這個app.use(reqHandler) – Cz01

+0

哈哈!這只是代碼的一部分。我的意思是,我們處理請求的代碼。謝謝! – Sandy

-1

req.body也可以在被訪問時

內容類型: 「應用程序/ x WWW的形式進行了urlencoded」

read this
在你的情況,您的內容類型爲application/json「

所以嘗試改變內容類型而從JS

向所述服務器發送到「應用程序/ x WWW的形式進行了urlencoded」

url encode參數

也溶液可以是

// fire request 
request({ 
    url: url, 
    method: "POST", 
    json: true, 
    headers: { 
     "content-type": "application/json", 
    }, 
    body: JSON.stringify(requestData) 
}, ... 
0

親愛的你設置身體分析器網址編碼爲真

// configure the app to use bodyParser() 
app.use(bodyParser.urlencoded({ 
    extended: true 
})); 

,並通過打印req.body檢查,這對我和可能適用於ü也

+0

謝謝拉坦。將嘗試並保持發佈。 – Sandy

相關問題