使用POSTMAN时在Node.js中显示空输出

时间:2018-09-13 07:42:59

标签: javascript node.js

我正在使用POSTMAN来测试我与Node.Js的API调用。当我将POST请求从POSTMAN发送到Node服务器时,console.log()中显示为空响应。

 const express = require('express');
 const bodyParser = require('body-parser');

 var app = express();
 var port = process.env.PORT || 3000;

 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({extended:true}));

 router.get('/',(req,res) => {

     console.log("Name:" +req.body.name);
     res.end();
 });

 app.listen(port,(req,res) =>{

     console.log("Server is running at:" +port);
  });

现在,我正在URL = localhost:3000 /上发送POSTMAN请求,并且数据是

 Key: name and Value: John

在控制台中,它显示类似错误

 TypeError: Cannot read property 'name' of undefined

2 个答案:

答案 0 :(得分:0)

您已在express框架中将请求定义为get:  router.get

,您说您正在发送POST。 改变另一件事

答案 1 :(得分:0)

您需要像这样将方法更改为POST:

router.post('/',(req,res) => {

  console.log("Name:" +req.body.name);
  res.end();
});

此外,您还需要使用以下选项来发布POSTMAN: enter image description here

您应该得到结果:

enter image description here