【问题标题】:Do not get a valid response from API in React-Nodejs project在 React-Nodejs 项目中没有从 API 获得有效响应
【发布时间】:2021-08-02 18:13:16
【问题描述】:

我正在使用 Express.js 为我的 React 应用程序构建一个 REST API。

这是我从前端调用 API 的地方:

const signIn = async () => {
    const user = await fetch(`${SERVER_URI}/users/signup`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email,
        password,
      }),
    })
    console.log(user);
  };

在 API 上:

router.post("/users/signup", async (req, res) => {
  try {
    let user = new User({
      name: req.body.name,
      email: req.body.email,
      password: bcrypt.hashSync(req.body.password, 10),
    });

    await user.save();
    const token = await user.generateAuthToken();
    if (!user) {
      return res.status(400).send("User could not be created");
    }

    res.status(200).send({ user, token });
  } catch (error) {
    console.log(error);
    res.status(500).send(error);
  }
});

用户在数据库中成功创建,但是当我记录从 API 返回的响应时,这是我在 Chrome 中看到的:

Response {type: "cors", url: "http://localhost:3002/users/signup", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3002/users/signup"
[[Prototype]]: Response

我应该得到刚刚与令牌一起创建的新用户对象。

我在这里做错了什么?

【问题讨论】:

  • 在你返回res.status(200)....之前你能console.log(user)console.log(token)吗?它会返回您所期望的吗?问题可能出在这些函数中
  • 果然,新创建的用户对象和令牌。

标签: node.js reactjs mongodb express


【解决方案1】:

fetch 函数返回一个Response 对象。您可以使用response.json() 获取包含您返回数据的对象,即{ "user": ..., "token": ... }

预期用途:

const signIn = async () => {
    const response = await fetch(`${SERVER_URI}/users/signup`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            email,
            password,
        }),
    });
    console.log(await response.json()); // { "user": ..., "token": ... };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    相关资源
    最近更新 更多