为什么浏览器中的 fetch 会向我的 API 发送一个空的 body,而不像像 Insomnia 这样的 API 客户端

Why does fetch in the browser send an empty body to my API unlike a API Client like Insomnia

我目前正在尝试使用 Mongo 数据库创建登录系统,但是当我尝试获取 POST 登录凭据到我的 express.js API 通过 Chrome 浏览器。与在任何浏览器中不同,它在我使用 Insomnia Client 时有效。我个人认为问题出在代码的 header 或中间件部分。我很感激我的问题可能出在哪里的每一个迹象。


代码:

登录函数:

async function login() {
  const data = getUserDataEncrypted(); //gets username and password

  await fetch(url + "/checkUser/login", {
    method: "POST",
    mode: 'cors',
    headers: {
      "Content-Type": "application/json"
  },
    body: JSON.stringify(data)
  }).then(res => {
    console.log(res.json());
  });
}

使用的中间件:

require('dotenv').config();

const express = require("express");
const app = express();
const mongoose = require('mongoose');

app.use(require("cors")());
app.use(express.json());
app.use(require("morgan")("combined"));

服务器端:

router.post('/login', async (req, res) => {
    try {
        const user = await User.find({ username: req.body.username });

        if (user[0].password === req.body.password) {
            res.send({
                message: "Successfull Login",
                login: true
            });
            return;
        } else {
            res.send({
                message: "Password incorrect",
                login: false
            });
            return;
        }
    } catch (error) {
        res.send({
            message: error.message,
            req: req.body
        });
    }
});

用户数据:

async function getUserDataEncrypted() {
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;

  password = await SHA256Encyption(password);

  const data = {
    username: username,
    password: password
  }

  return data;
}

图片:

在登录函数中,尝试console.log来自getUserDataEncrypted()的数据。

如果它为 null 或 undefined 尝试使用 await。

等待 getUserDataEncrypted();

const data = getUserDataEncrypted(); //gets username and password

您需要进行一些基本调试。如果您记录了 data 的值,那么问题就很明显了。

getUserDataEncrypted 被标记为 async 所以它 returns 一个承诺。

console.log(JSON.stringify(Promise.resolve()));

承诺字符串化为空对象。

您需要 await 承诺或在 then() 回调中获取(并使用)其结果。