为什么我的 fetch() 发送的是空 JSON 正文?

问题描述 投票:0回答:1

我一直在尝试使用 fetch 发送 JSON 数据,但后端收到一个空对象。 在我的 Client JS 中我有

const user = "company1";
const username = "muneeb";

const data = {user, username};

fetch("http://127.0.0.1:3000/users/api/login", {
    method: 'POST',
    body: JSON.stringify(data)
}).then((response) => {
    console.log(response);
});

服务器端有:

router.post('/users/api/login', async (req, res, next) => {

    try {
        // console.log(request.body);
        const request = JSON.stringify(req.body);

        let imageTitles = [];
        console.log(request);

        *its random from here on out but you get the idea*

        await components.getImages(imageTitles);
        const finalKey = imageTitles.join("");
        let images = await components.output(req.body.user ,req.body.username);
        res.send(components.jsonConverter(imageTitles, images)); //---Top priority
        db.setPassword(req.body.user, req.body.username , finalKey);
    } catch (err) {
        console.log(err);
        res.send(err).sendStatus(500);
    };
})

我已经尝试过的一些事情:

它在失眠症(邮递员)中完美运作。

express.json() 存在,它帮助我从未定义到空白 JSON。

我已启用 cors 设置。

现在就这样。

javascript json rest fetch-api
1个回答
3
投票

主体解析器

express.json
仅适用于带有
Content-Type: application/json
的请求。您必须将内容类型添加到您的
fetch
调用中:

fetch("http://127.0.0.1:3000/users/api/login", {
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    'Content-Type': 'application/json'
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.