React中Axios登录方法调用异常:后端返回JWT但控制台输出异常
登录请求返回undefined的问题分析与解决
问题场景
组件侧调用登录方法的代码:
const requestLogin = (username, password) => { let response = authService.login(username, password); console.log("test1"); console.log(response); console.log("test2"); }
服务端请求的login方法代码:
export function login(username, password) { axios({ method: "post", url: "http://localhost:8080/auth/login", data: {username: username, password: password} }).then(res => { if (!res.ok) { throw Error('Network Error'); //error from axios } return res.json(); }).catch(err => { console.log(err.message) //to display the error to your user just use the useState to define your error }) }
后端已在Network中正常返回JWT Token,但控制台输出test1、undefined、test2,无法验证响应并跳转页面。
问题原因
- login函数未返回Promise:axios请求是异步操作,原login函数没有返回axios调用的Promise,导致组件中
response直接拿到undefined。 - axios响应处理错误:axios的响应对象没有
ok属性,且axios会自动解析JSON响应为res.data,不需要调用res.json()(这是fetch API的用法)。另外,axios会将HTTP错误状态码(4xx/5xx)直接抛入catch,无需手动判断。 - 异步结果未正确等待:组件中直接同步赋值,没有用
await或.then()等待异步请求完成,所以拿不到实际响应数据。
修正后的代码
1. 修正authService的login函数
export function login(username, password) { // 返回axios的Promise,让组件可以等待异步结果 return axios({ method: "post", url: "http://localhost:8080/auth/login", data: {username, password} }) .then(res => { // axios自动解析JSON,直接返回后端返回的data return res.data; }) .catch(err => { console.error('登录失败:', err.message); throw err; // 抛出错误,让组件能捕获并处理 }) }
2. 修正组件侧的requestLogin函数
使用async/await方式(更直观易读):
const requestLogin = async (username, password) => { try { console.log("test1"); const response = await authService.login(username, password); console.log(response); // 这里能拿到后端返回的JWT数据 console.log("test2"); // 验证登录结果,比如检查返回数据中是否包含token if (response.token) { // 执行页面跳转,例如使用react-router的navigate方法 navigate('/dashboard'); } } catch (err) { // 处理登录失败的逻辑,比如提示用户账号密码错误 console.error('登录出错:', err); } }
或者使用.then()链式调用方式:
const requestLogin = (username, password) => { console.log("test1"); authService.login(username, password) .then(response => { console.log(response); console.log("test2"); if (response.token) { navigate('/dashboard'); } }) .catch(err => { console.error('登录出错:', err); }) }
内容的提问来源于stack exchange,提问作者Chris Garsonn
相关产品推荐
相关产品推荐

