2017-07-10 89 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

不要忘记给予好评的答案,如果你发现它有用。