BodyParser无法使用POSTMAN解析请求

时间:2019-07-09 00:29:33

标签: node.js api body-parser

由于某种原因(我无法找出原因),bodyParser无法解析来自我的api的请求(标​​题和内容)。它们似乎是undefined

app.js

const EXPRESS = require('express');
const FEED_ROUTES = require('./routes/feed');
const BODY_PARSER = require('body-parser');
const APP = EXPRESS();

APP.use(BODY_PARSER.json());
APP.use(BODY_PARSER.urlencoded({ extended: false }));
APP.use('/feed', FEED_ROUTES);

APP.listen(8080);

控制器js

exports.getPosts = (req, res, next) => {
  res
    .status(200)
    .json({ posts: [{ title: 'test', content: 'This is a post ' }] });
};

exports.createPost = (req, res, next) => {
  const title = req.body.title;
  const content = req.body.content;
  console.log(title);
  res.status(201).json({
    message: 'Post created succesfully!',
    post: { id: new Date().toISOString(), title: title, content: content }
  });
};

POSTMAN打印此:

{
    "message": "Post created succesfully!",
    "post": {
        "id": "2019-07-09T00:24:57.129Z"
    }
}

作品 enter image description here

不工作 enter image description here

1 个答案:

答案 0 :(得分:1)

您需要使用

发送请求
  1. HTTP标头Content-Type: application/json
  2. 有效的JSON正文

要使用Postman v7.2.2实现以上功能,请参见下面的屏幕截图

Send JSON request using Postman