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

前端Axios发送请求,Express后端未接收问题求助

解决思路

以下是针对你的问题的排查方向和解决方案:

1. 处理跨域(CORS)问题

浏览器会拦截跨域请求,而Postman不受此限制,这是最常见的原因。给Express后端添加CORS中间件:

首先安装cors包:

npm install cors

然后在后端代码中启用:

const cors = require('cors');
// 在路由之前注册中间件
app.use(cors());

如果需要更严格的配置(比如只允许前端域名),可以指定origin:

app.use(cors({ origin: 'http://localhost:3000' }));

2. 修复Axios请求写法

Axios会自动将JavaScript对象序列化为JSON,并设置正确的Content-Type头,你不需要手动调用JSON.stringify。修改前端请求代码:

const handleSignUp = async () => {
  console.log("Username: ", username);
  console.log("Email: ", email);
  console.log("Password: ", password);
  axios("http://localhost:5000/sign-up", {
    method: 'POST',
    // 可去掉手动设置的Content-Type,Axios会自动处理
    data: { username, email, password }, // 直接传对象
  })
  .then((response) => console.log(response))
  .catch((err) => console.log(err));
};

3. 给后端添加错误捕获

你的后端async函数没有错误处理,如果Prisma创建用户时抛出异常(比如字段重复、验证失败),请求会一直处于Pending状态,因为没有返回响应。添加try/catch:

app.post('/sign-up', jsonParser, async (req: Request, res: Response) => {
  try {
    console.log("Received POST request:", req.method, req.url);
    console.log("Request body:", req.body);
    const newUser = await prisma.user.create({data: req.body});
    console.log("Created new user:", newUser);
    res.status(200).json(newUser);
  } catch (error) {
    console.error("Create user failed:", error);
    res.status(500).json({ message: "Failed to create user", error: error.message });
  }
});

4. 检查浏览器Network面板

打开浏览器开发者工具的Network标签,查看该POST请求的详情:

  • 确认Request Headers中的Origin和Content-Type是否正确
  • 查看是否有CORS相关的报错信息
  • 检查后端是否有返回响应(哪怕是错误响应)

5. 尝试使用代理配置(可选)

在React项目的package.json中添加代理配置,这样前端请求可以省略域名,直接写相对路径,同时避免跨域问题:

{
  "proxy": "http://localhost:5000"
}

然后修改前端请求地址:

axios("/sign-up", {
  method: 'POST',
  data: { username, email, password },
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 02:50:14