2017-07-10 90 views
0

我正在使用Express JS(v 4.15.3)構建節點api。nodejs-無法獲取表單數據

我試圖從表單發送值(通過POSTMAN客戶端)。我無法取回它。

這是我的形式

頁眉指定

enter image description here

無頭

enter image description here

這是怎麼了,我試圖把它拿來:

router.post('/login',function(req, res, next) { 
    var email= req.body.email; 
    //var email= req.query.email; //also tried this 
    res.json({ 
     value: email 
    }); 
}); 

我沒有收到錯誤。

注意:我已經包含了body parser。

var bodyParser = require('body-parser'); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json()); 

誰能告訴我爲什麼我沒有得到價值?謝謝! 這是我第一次嘗試學習Node JS。

+0

你嘗試過'application/json'作爲內容類型嗎? –

回答

1

您的代碼似乎完全正常。雖然問題與您從POSTman客戶端發送請求的方式有關。

當您發送使用使用表單數據要求,郵遞員發送該請求作爲多/ form-data的,這實際上將您的數據格式如下:

POST /api/login HTTP/1.1 
Host: localhost:3000 
Content-Type: application/x-www-form-urlencoded 
Cache-Control: no-cache 

----WebKitFormBoundaryE19zNvXGzXaLvS5C 
Content-Disposition: form-data; name="email" 

[email protected] 
----WebKitFormBoundaryE19zNvXGzXaLvS5C 

對於多/ form-data請求您需要使用multer中間件,如果您確實需要使用應用程序上傳文件。但是,對於你的情況,你可以只發送數據,而無需使用使用表單數據(取消選中使用表單數據複選框),並設置內容類型頭來:

Content-Type: application/x-www-form-urlencoded 

因此,所有這些修改後您的原始Web請求看起來應該象下面這樣:

POST /api/login HTTP/1.1 
Host: localhost:3000 
Content-Type: application/x-www-form-urlencoded 
Cache-Control: no-cache 

[email protected] 

郵遞員屏幕捕獲建立請求和響應是如下:

POSTman screen capture for building the request and response

請求和響應郵遞員畫面捕獲如下:

POSTman screen capture for Raw request and response

希望這會幫助你。

0

嘗試設置JSON格式的Content-Type爲application/JSON和身體原這樣寫:

{ 
    "email":"[email protected]" 
} 

這裏有,你可以參考的圖像。

enter image description here

enter image description here

不要忘記給予好評的答案,如果你發現它有用。