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

使用Axios请求/api/auth/signin返回404,Postman请求正常求助

接口请求排查:Postman成功但Axios返回404

问题现象

调用http://localhost:8800/api/auth/signin接口时,Postman可正常发起请求并得到响应,但使用TypeScript中的Axios发送POST请求时返回404错误。

Postman请求信息

请求体内容:

{"email":"test1@test1.com","pw":"test1"}

Axios请求代码

const response = await axios.post(
        `http://localhost:8800/api/auth/signin`,
        {
          email: `${username}@${username}.com`,
          pw: password,
        }
      );

后端Express配置代码

// CORS on ExpressJS
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Content-Type", "application/json");
    next();
});

app.use(express.json()); // Allowed come in json data
app.use("/api/users",userRouters)
app.use("/api/dailyPlan",dailyPlanRouters)
app.use("/api/auth",authRouters)

app.use((err,req,res,next)=>{
    const status=err.status || 500;
    const message = err.message || "Something went wrong";
    return res.status(status).json({
        success:false,
        status,
        message,
    })

})
app.listen(8800,()=>{
    connect();
    console.log("Connected to Server");
})

排查方向与解决方法

1. 验证请求体参数的正确性

Axios中email是通过${username}@${username}.com动态生成的,需确认前端传入的username和password是否与Postman一致:

  • 在请求前打印参数,确认生成的email和pw值:
    console.log('请求参数:', { email: `${username}@${username}.com`, pw: password });
    
  • 确保password的值为test1,与Postman请求体匹配。

2. 显式指定Axios请求头

虽然Axios默认会为JSON请求体设置Content-Type: application/json,但手动显式指定可避免潜在的头信息问题:

const response = await axios.post(
  `http://localhost:8800/api/auth/signin`,
  {
    email: `${username}@${username}.com`,
    pw: password,
  },
  {
    headers: {
      'Content-Type': 'application/json',
    },
  }
);

3. 检查后端路由定义

确认authRouters中是否正确配置了POST /signin路由:

  • 路由文件示例(需保证路由无前缀冗余):
    const express = require('express');
    const router = express.Router();
    
    router.post('/signin', (req, res) => {
      // 登录逻辑处理
    });
    
    module.exports = router;
    
  • 若后端路由定义为POST /api/auth/signin,则authRouters内的路由必须是/signin,不能包含/api/auth前缀。

4. 确认请求体解析是否正常

在authRouters的signin路由中打印req.body,检查是否正确解析了Axios发送的请求体:

router.post('/signin', (req, res) => {
  console.log('收到的请求体:', req.body);
  // 后续逻辑
});
  • 若req.body为空,说明express.json()未正确解析请求体,需确认Axios发送的是标准JSON格式,且请求头Content-Type为application/json。

5. 检查请求路径的一致性

对比Axios的请求URL与Postman的URL,确保无拼写错误、大小写差异或多余斜杠,比如http://localhost:8800/api/auth/signin必须完全匹配后端路由路径。


内容的提问来源于stack exchange,提问作者Rachel Duan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:45:06