You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

前端调用带requireAuth中间件的接口无返回,直接调用正常是什么原因?

问题根因

你遇到的问题是身份校验中间件、跨域配置、AJAX请求逻辑三者不兼容导致的,具体原因如下:

  • 跨域配置不匹配:你请求带了withCredentials: true,后端必须同时满足两个CORS要求:① Access-Control-Allow-Origin不能设为通配符*,必须明确指定为前端地址http://localhost:3000;② 必须设置Access-Control-Allow-Credentials: true。如果CORS配置不符合要求,浏览器会直接拦截响应,await后的代码不会执行,自然没有控制台输出。
  • 中间件返回逻辑不兼容AJAX请求:你在requireAuth里校验失败直接返回302重定向,AJAX请求不会触发页面跳转,只会自动跟随重定向拿到http://localhost:3000/home的HTML响应,axios默认按JSON解析就会报错,代码直接进入异常分支,你没有写try/catch捕获错误,所以看不到报错提示。
  • 你直接在浏览器地址栏调用接口属于普通页面请求,不受CORS规则限制,且浏览器会自动处理302重定向,所以可以正常拿到响应;移除中间件后不会触发身份校验的重定向逻辑,接口直接返回JSON,因此前端可以正常渲染。
  • 你的路由代码存在小的语法问题:.then(console.log("test"))是立即执行console.log,不是请求成功后执行,不过这个不是核心故障点。

修复步骤

  1. 修正后端CORS配置,以express的cors包为例:
const cors = require('cors');
app.use(cors({
  origin: 'http://localhost:3000',
  credentials: true
}));
  1. 调整requireAuth中间件的返回逻辑,AJAX请求校验失败不要返回重定向,返回JSON格式的错误码:
const jwt = require("jsonwebtoken");

const requireAuth = (req, res, next) => {
  const token = req.cookies.jwt;
  console.log("test token:" + token);

  if (token) {
    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decodedToken) => {
      if (err) {
        console.log(err.message);
        res.status(401).json({ code: 401, msg: '身份校验失败' });
      } else {
        console.log(decodedToken);
        next();
      }
    });
  } else {
    console.log("test");
    res.status(401).json({ code: 401, msg: '缺少身份凭证' });
  }
};

module.exports = { requireAuth };
  1. 前端axios请求添加try/catch捕获异常,方便排查问题,同时处理身份校验失败的场景:
useEffect(() => {
    (async () => {
      try {
        const result = await axios("http://localhost:5000/projects", {
          withCredentials: true,
        });
        setProjects(result.data);
        console.log(result.data);
      } catch (err) {
        console.error('请求失败:', err);
        // 身份校验失败时手动跳转到对应页面
        if (err.response?.status === 401) {
          window.location.href = 'http://localhost:3000/home';
        }
      }
    })();
}, []);
  1. 修正路由的Promise链式调用写法:
router
  .route("/")
  .all(requireAuth)
  .get((req, res) => {
    Project.find()
      .then((projects) => res.json(projects))
      .then(() => console.log("test"))
      .catch((err) => res.status(400).json("Error: " + err));
  });

内容的提问来源于stack exchange,提问作者Christian Townsend

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:48:03