JavaScript POST 请求导致服务器端的请求正文为空

时间:2021-07-16 13:59:36

标签: javascript node.js express

我正在构建一个简单的金融应用程序来练习我的新手 JS 技能。客户端在 localhost:3000 上运行,服务器在 localhost:4001 上运行。

客户端代码:

async function addTransaction(id, date, description, header, amount) {
    await fetch('http://localhost:4001/transactions', {
        method: 'POST',
        body: JSON.stringify({id, date, description, header, amount})
    });
}

服务端代码:

const express = require('express');

const app = express();
const PORT = process.env.PORT || 4001;

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

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

function addTransaction(req, res) {
    console.log(req.body);
}

app.post('/transactions', addTransaction);

app.listen(PORT, () => console.log(`Listening on port ${PORT}...`));

我知道在这个论坛上也有人问过类似的问题,但没有一个给定的解决方案,比如在标题中添加 Content-type: application/json 对我有用。

有趣的是,从 Postman 发出发布请求实际上是有效的。

我希望任何人都可以提供帮助。

1 个答案:

答案 0 :(得分:1)

您未能设置 Content-Type 请求标头,因此正在应用默认值 (text/plain IIRC)。

由于客户端没有它正在发送 JSON,因此它不会触发您设置的 JSON 正文解析器。

fetch('http://localhost:4001/transactions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({id, date, description, header, amount})
});

由于这会将请求转换为预检请求,因此您需要配置您的服务器以在客户端发出 POST 请求之前处理预检 OPTIONS 请求。

目前您正在滚动自己的 CORS 处理:

<块引用>
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

不要那样做。使用 the cors middleware module 并按照说明进行 configure it for preflighted requests