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

URL正确但Fetch请求失败,404错误排查求助

问题分析与修复方案

核心问题:请求方法不匹配

前端发送的是POST请求,但后端路由注册的是GET请求,导致服务器找不到对应路由,返回404错误。

具体错误点

  1. 请求方法不匹配:前端fetch配置了method: "POST",但后端用app.get("/api/verify")注册路由,GET路由无法处理POST请求。
  2. 后端GET路由无法获取请求体:GET请求默认不携带请求体,即使前端传了数据,后端req.body也会是undefined,触发你写的!req.body判断返回404。
  3. 前端异步处理错误:response.json()是异步操作,你直接同步赋值后访问response.token,拿到的是Promise对象而非实际数据,导致token永远为undefined。

修复步骤

1. 修改后端路由为POST方法

同时确保已配置请求体解析中间件,否则无法读取req.body:

// 先在路由前配置body解析中间件
const express = require('express');
const app = express();
app.use(express.json()); // 必须配置,否则req.body为undefined

app.post("/api/verify", (req, res) => {
    console.log("function called");
    // 更精准的参数校验
    if (!req.body?.email || !req.body?.password) {
        res.status(400).send("缺少邮箱或密码");
        return;
    }

    const { email, password } = req.body;

    res.json({
        token: jwt.sign(
            {
                username: email,
                admin: email === "admin" && password === "admin",
            },
            KEY
        ),
    });
});

2. 修复前端异步逻辑

统一使用await处理异步操作,避免混用await和then,同时修正setMessage后的日志问题(setMessage是异步的,直接log状态值拿不到最新结果):

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
        const res = await fetch("http://localhost:8080/api/verify", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ email, password }),
        });

        if (!res.ok) {
            console.log("请求失败");
            setMessage("登录失败,请检查账号密码");
            return;
        }

        const data = await res.json();
        const token = data.token;
        if (token) {
            const json = jwt.decode(token);
            const welcomeMsg = `Welcome admin with token of ${json.username}`;
            setMessage(welcomeMsg);
            console.log(welcomeMsg); // 先存变量再日志,避免异步状态延迟
        } else {
            setMessage("Something went wrong");
        }
    } catch (error) {
        console.log("errrorrr:", error);
        setMessage("网络错误,请稍后重试");
    }

    //router.push("../homePage/home");
};

额外注意事项

  • 如果前后端端口不同(比如前端3000、后端8080),需配置CORS跨域:安装cors包后添加app.use(cors());。
  • 错误状态码要规范:参数缺失用400(客户端错误),而非404(路由不存在)。

内容的提问来源于stack exchange,提问作者MoeezMahmood Ramay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:10:24