获取 post 请求如果请求成功则不记录成功

fetching post request don't log success if the request succeed

我正在尝试注册新用户,当我发送 post 请求时,服务器很好地注册了用户,我可以在我的数据库中看到它们,但我看不到我的控制台中的成功日志(我可以捕获错误并将其记录在我的控制台中)。

服务器端代码:

var express = require("express");
const { Error } = require("mongoose");
const passport = require("passport");
var router = express.Router();
const User = require("../models/user");
const catchAsync = require("../utils/catchAsync");

router.post(
  "/register",
  catchAsync(async (req, res) => {
    try {
      const { email, username, password } = req.body;
      const user = new User({ email, username });
      await User.register(user, password);
    } catch (e) {
      throw new Error("Error signing up");
    }
  })
);

module.exports = router;

客户端代码:

  const sumbitHandler = async (data) => {
  const { username, email, password } = data;
  try {
    await fetch("http://localhost:9000/users/register", {
      method: "POST",
      body: JSON.stringify({
        username,
        email,
        password,
      }),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => {
        if (res && !res.ok) {
          throw new Error("ERROR");
        }
        console.log("Success");
      })
      .catch((e) => {
        console.log(e.message);
      });
  } catch (e) {
    console.log(e.message);
  }
};
  1. 您正在混合使用 async/await 风格和较旧的 .then() Promise 风格。二选一(我强烈推荐async/await

  2. 您没有将 fetch 的响应转换为 JSON,使其处于 Promise 状态。

  3. 您的服务器从不响应客户端!您需要添加 res.end()res.send()res.json() 或其他内容。

    const sumbitHandler = async (data) => {
        const { username, email, password } = data;
        try {
    
            const response = await fetch("http://localhost:9000/users/register", {...});
    
            const serverResponse = await response.text(); // or response.json() if your servers sends JSON back
    
            console.log("Success! serverResponse is = ", serverResponse ); // "Done!"
    
        } catch (e) {
            console.log(e.message);
        }
    };

服务器:

...
await User.register(user, password);
res.send("Done!"); // or res.json({ status : "ok" }); etc.