使用Axios实现登录:服务端响应传递至客户端时始终为undefined
解决Axios登录请求后客户端响应为undefined的问题
你的核心问题是Login函数没有返回axios请求的Promise结果,导致前端调用后拿到的响应始终是undefined,以下是具体修复方案和优化建议:
1. 修复Login函数的返回值
你写的axios请求代码虽然在.then里return了response.data,但整个axios调用的Promise没有被返回给Login函数的调用者。需要把整个axios请求表达式return出去:
修复后的Login函数代码
const Login = async (email: string, password: string) => { // 关键:返回整个axios请求的Promise链 return await axios .post( 'http://127.0.0.1:3333/auth/signin', { email: email, password: password }, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }, ) .then((response) => { const accessToken = response.data.accessToken || ''; const refreshToken = response.data.refreshToken || ''; if (accessToken !== '' && refreshToken !== '') { cookies().set('access_token', accessToken); cookies().set('refresh_token', refreshToken); console.log('Authenticated successfully:', response.data); } return response.data; }) .catch((error) => { console.error('Authentication failed:', error); // 建议抛出错误而非返回对象,让前端能捕获失败状态 throw error; }); };
2. 优化前端登录处理代码
前端代码同时混用await和.then,可读性较差,建议统一风格:
方案一:仅使用await(推荐)
const handleLogin = async (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => { e.preventDefault(); try { const response = await Login(email, password); console.log('response:', response); router.push('/profile'); } catch (error) { // 这里可以添加登录失败的用户提示逻辑 console.error('登录失败:', error); } };
方案二:仅使用.then/.catch
const handleLogin = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => { e.preventDefault(); Login(email, password) .then((response) => { console.log('response:', response); router.push('/profile'); }) .catch((error) => { console.error('登录失败:', error); }); };
3. 额外注意事项
- 请求头与请求体不匹配:你设置了
application/x-www-form-urlencoded头,但请求体是JSON对象,后端可能无法解析参数。如果后端期望表单格式,需要用qs.stringify({ email, password })转换请求体;如果后端期望JSON,应将请求头改为application/json。 - 错误处理逻辑:原catch块返回
{ props: error }会让前端误以为登录成功,改为抛出错误可以让前端正确捕获失败状态,做对应的错误提示。
内容的提问来源于stack exchange,提问作者user1688346
相关产品推荐
相关产品推荐

