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

Node.js中POST请求报404错误,GET请求正常,求排查原因

问题分析与解决

你的POST请求出现404的核心原因有两个,逐个修复即可:

1. 客户端Axios请求参数传递错误

Axios的post方法语法为:axios.post(url[, data[, config]]),你错误地把请求数据放到了config的body字段中,还将config作为了第二个参数(该位置本该用于传递请求数据)。这种错误的参数传递会导致请求格式不符合服务端预期,甚至被路由识别为无效请求。

修正后的客户端代码:

const writePost = async () => {
    axios.defaults.withCredentials = true;
    // 单独提取请求数据
    const postData = {
        title: writeData.title,
        content: writeData.content,
        register: writeData.register,
    };
    const config = {
        headers: {
            withCredentials: true,
        },
    };
    try {
        const res = await axios.post("http://localhost:8000/api/insert", postData, config);
        console.log(res);
        console.log(res.config);
    } catch (error) {
        console.log("write error", error);
    }
};

若你偏好将数据放在配置中,需使用data字段而非body:

const config = {
    headers: { withCredentials: true },
    data: {
        title: writeData.title,
        content: writeData.content,
        register: writeData.register,
    },
};
// 此时第二个参数传空对象或null
const res = await axios.post("http://localhost:8000/api/insert", {}, config);

2. 服务端缺少服务器启动代码

你提供的服务端代码未添加app.listen()来启动HTTP服务器,这会导致服务根本没有监听8000端口,所有请求都会失败(推测你实际运行的服务端代码包含该逻辑,但贴出的代码遗漏了)。

服务端补充代码:

在服务端代码末尾添加:

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

额外验证项

  • 当前服务端CORS配置cors({ credentials: true, origin: true })允许带凭证的跨域请求,无需调整。
  • body-parser中间件配置app.use(bodyParser.json())和app.use(bodyParser.urlencoded({ extended: true }))可正确处理JSON、表单格式的请求体,配置正常。

内容的提问来源于stack exchange,提问作者한대현

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:25:24