【问题标题】:JSON Request body always empty in Express server在 Express 服务器中 JSON 请求正文始终为空
【发布时间】:2021-11-27 16:07:28
【问题描述】:

我正在使用 express 构建一个小型服务器和网站。 现在我想使用编码为 JSON 的简单凭据向我的快递服务器发送一个 POST 请求。 我的问题是无论我尝试什么,我的请求正文在服务器端总是空的。我确信在前端的值在那里,我的代码控制台。在发送请求之前记录正确的用户名和密码。我可以在 chrome 开发工具的网络面板中看到发送到服务器的正确有效负载 前端代码:

    <script>

        const username_input = document.getElementById('username');
        const password_input = document.getElementById('password');
        const submit_registration = document.getElementById('submit_registration');
        
        
        submit_registration.addEventListener('click', (event) => {
            const username = username_input.value;
            const password = password_input.value;
            console.log(username, password);
            
            fetch('/register', {
                method: 'POST',
                header: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    'username': username,
                    'password': password
                })
            })
            .then(raw_response => raw_response.json())
            .then(response => console.log(response))
            .catch(err => console.log(err))
            
        });
    </script>

我还尝试将一个简单的 POST 请求卷曲到我的服务器。我使用的卷曲:

curl -H POST "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/register

我的服务器代码中的请求正文再次为空。 我猜问题出在后端的某个地方,但我不确定,所以我通过 curl 添加了请求并获取只是为了确定。 这是我处理 POST 请求的快速代码:

const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());

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

    console.log(req.body);
    res.status(200).send('Ok');

});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
});

结果总是空的大括号,但假设其中有用户名和密码,就像上面的请求中的发送一样,我不明白为什么它总是空的。 我的 Express 版本是 4.17,所以 express.json() 应该可以工作。

我必须补充一点,当我使用 html 表单并通过 application/x-www-form-urlencoded 对数据进行编码并在我的 express 应用程序中使用

对其进行解码时
app.use(express.urlencoded({ extended: true}))

成功了。我收到了用户名和密码,但现在使用 json,后端的正文始终为空。

我很沮丧

【问题讨论】:

  • 尝试在您的 fetch 调用中将标头更改为标头。
  • curl -H POST "Content-Type: application/json" 不发送 content-type 头,使用curl -X POST -H "Content-Type: application/json"
  • @NeonD 这有点尴尬,但解决了它。如果需要,请创建一个答案,我将其标记为已接受的答案。

标签: json api express fetch backend


【解决方案1】:

在您的提取请求中将header 属性更改为headers

【讨论】:

  • 我很高兴知道这个建议奏效了!阅读您的代码几次后才注意到它,因为一切看起来都不错。
【解决方案2】:

试试 res.status(200).json('Ok');

【讨论】:

  • 感谢Tipp,@NeonD 解决了我的问题。但你的回答解决了我接下来会面临的另一个问题
猜你喜欢
  • 2021-05-29
  • 2019-10-24
  • 2021-02-01
  • 2021-06-18
  • 2015-09-08
  • 1970-01-01
  • 2016-10-10
  • 2016-06-01
  • 2021-03-04
相关资源
最近更新 更多