【问题标题】:Empy req.body in NodeJs, ExpressNode Js,Express中的空req.body
【发布时间】:2021-04-07 00:39:14
【问题描述】:

我正在尝试通过正文中的 POST 方法将 json 发送到我的 nodeJs 应用程序。 为此,我使用 POSTMAN 创建请求,并使用正确的 consnt-type 标头和正文 JSON 行。尽管控制台中返回的消息为“OK”,但 req.body 为 {} 为空。 你知道我的代码有什么问题吗?

const bodyParser = require('body-parser');
const { Client } = require('pg');
const express = require('express');
const app = express();

// create application/json parser
const jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
const urlencodedParser = bodyParser.urlencoded({ extended: false })

const hostname = '127.0.0.1';
const port = 3000;

const dbSchema = 'public';

const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'postgres',
    password: '123123',
    port: 5432,
});

client.connect();

/* =========== Some Initialize staff =============== */

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))

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

app.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

/* =========== FROM HERE =============== */

app.post('/post-test', urlencodedParser, (req, res) => {
    console.log('Got body:', req.body);
    res.sendStatus(200);
});


app.get('/',(req,res)=>{
    res.status(200).send('Get Ready for something awesome!\n');
});

enter image description here

【问题讨论】:

  • 我通常使用 - route.use(express.json());route.use(express.urlencoded({extended:true})); 在您的情况下,routeapp。新版 Express 不用body-parser
  • 当我添加以下行时:app.use(express.json()); app.use(express.urlencoded({extended:true}));开始出现以下错误:SyntaxError: Unexpected token in JSON at position 92
  • 你用的express是什么版本的?
  • express": "^4.17.1",
  • urlencodedParser 是为了什么?如邮递员屏幕截图所示,输入 JSON 似乎有问题?

标签: node.js express


【解决方案1】:

你应该使用app.use(bodyParser.json());,在你的代码中const jsonParser = bodyParser.json()这个没有被使用。

更新:或者你可以将jsonParser中间件直接应用到post路由:

app.post("/post-test", jsonParser, (req, res) => {
  console.log("Got body:", req.body);
  res.json({ ...req.body });
});

【讨论】:

  • 我添加了:app.use(bodyParser.json());运行请求时开始出现以下错误:位置 92 处的 JSON 中的意外令牌
  • 你能在邮递员中提供你的身体而不是图像吗?
  • 我在 app.post(...) 中添加了“jsonParser”,得到了同样的错误:位置 92 处的 JSON 中的意外标记
  • { "username": "newHere", "fullname": "homeless", "email": "alwaysYoung@gmail.com", "psw": "password", "inviterId": 1 , }
  • 去掉"inviterId": 1后面的逗号,
【解决方案2】:

无法弄清楚发生了什么,我发布了适合我的代码 -

    let express = require('express'); 
    let app = express();
    const authorRoute = express.Router();
    authorRoute.use(express.json());
    authorRoute.use(express.urlencoded({extended:true}));
    authorRoute.post('/post-test', async (req, res) => {//req.body});
    app.use(authorRoute);

另外,请确保使用格式正确的 JSON 进行测试。 版本“快递”:“^4.17.1”,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-08
    • 2020-08-20
    • 2017-08-30
    • 2019-01-03
    • 2020-09-21
    • 2020-01-08
    • 1970-01-01
    • 2016-02-15
    相关资源
    最近更新 更多