简体   繁体   English

Node.js express - POST 请求的正文始终为空

[英]Node.js express - body of POST request is always empty

I am trying to read the body of POST request using Express in Node.JS framework.我正在尝试使用 Node.JS 框架中的 Express 读取 POST 请求的正文。 I send a HTTP POST request using HTML form.我使用 HTML 表单发送 HTTP POST 请求。 I detected a POST request on WireShark with the following data:我在 WireShark 上检测到一个带有以下数据的 POST 请求:

在此处输入图片说明

This shows that the request is sent successfully.这表明请求发送成功。 I expected JSON format, which is the one that Express successfully parsed for me, but this format just doesn't seem to work no matter what I tried.我期待 JSON 格式,这是 Express 为我成功解析的格式,但无论我尝试什么,这种格式似乎都不起作用。 My current implementation goes like this:我目前的实现是这样的:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json()

//Import static files
app.use(express.static('../public'))

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

app.post('/', jsonParser, (req, res) => {
    console.log(req.body);
    res.send(200);
});

app.listen(port, () => console.log("Server started"));

No matter what I try from other posts, it still does not seem to return me any data.无论我从其他帖子中尝试什么,它似乎仍然没有返回任何数据。

在此处输入图片说明

Does anyone have an idea how to fix this problem?有谁知道如何解决这个问题?

Why to you use 'jsonParser' in the app route?为什么要在应用程序路由中使用“jsonParser”? Try something like:尝试类似:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM