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

使用Axios调用Login接口时出现Error 404问题求解决

解决Login接口404错误的方案

404错误核心原因是请求的API路径不存在,结合你的代码,可从以下几点修正:

1. 修正API端点路径的大小写

多数后端框架(如Express、Spring Boot)的路由规则区分大小写,你当前请求的http://localhost:3000/Login大概率不符合后端实际暴露的路径,通常后端登录接口会用小写的/login。修改url字段:

url: 'http://localhost:3000/login'

2. 简化请求体的序列化操作

你手动使用JSON.stringify处理请求体,但axios在设置Content-Type: application/json时,会自动将JavaScript对象序列化为JSON字符串,无需手动转换。简化代码如下:

// 直接构造对象,无需JSON.stringify
const formData = {
  username: username,
  password: password
};
// config中的data直接传入该对象
data: formData

3. 验证后端服务状态

  • 确认localhost:3000的后端服务是否正常启动
  • 用Postman或浏览器调试工具直接发送POST请求到http://localhost:3000/login(携带{"username":"xxx","password":"xxx"}参数),验证后端是否能正常响应,排除前端代码外的问题

修正后的完整代码

document.getElementById('loginForm').addEventListener('submit', async(event) => {
  event.preventDefault();
  const username = document.getElementById('Username').value;
  const password = document.getElementById('Password').value;
  const formData = {
    username: username,
    password: password
  };
  let config = {
    method: 'POST',
    url: 'http://localhost:3000/login',
    headers: { 'Content-Type': 'application/json' },
    data: formData
  };
  try {
    const response = await axios.request(config);
    console.log(response.data);
    alert('Successfully Logged In');
  } catch (err) {
    console.log(err);
    console.log(err?.response); // 用可选链避免未定义报错
    alert(err.message);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:24:51