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

如何将loginRequest函数的API响应传递至Login.js组件?

解决方案

要把服务器响应传递到Login.js并根据结果决定跳转,需要调整两个文件的代码:

1. 修改api.js中的loginRequest函数

让函数返回axios请求的Promise,并在成功时返回响应数据,失败时抛出错误,这样调用方可以获取结果或捕获异常:

export function loginRequest({ values }) {
  return axios.post('http://localhost/api/auth/applogin', {
    email: values.email,
    password: values.password
  }).then((res) => {
    Cookies.set('token', res.data.access_token)
    console.log('logged in successfully.');
    return res; // 将响应返回给调用组件
  }).catch((err) => {
    console.log(err);
    throw err; // 抛出错误,让调用组件可以处理失败逻辑
  });
}

2. 修改Login.js中的loginHandler函数

通过await获取loginRequest的返回结果,用try/catch/finally处理成功、失败和loading状态:

const loginHandler = async (values) => {
  setLoading(true);
  try {
    const res = await loginRequest({ values });
    // 登录成功后执行跳转
    await navigate('/main');
    // 这里可以根据res做其他逻辑,比如存储用户信息到state
  } catch (err) {
    // 登录失败时的处理,比如显示错误提示
    console.error('登录失败:', err);
  } finally {
    // 无论成功失败,都关闭loading
    setLoading(false);
  }
}

关键说明

  • 原loginRequest函数没有返回Promise,导致Login.js无法等待请求完成并获取结果,修改后返回axios请求本身(axios.post默认返回Promise)。
  • 使用try/catch可以捕获登录失败的异常,避免代码阻塞;finally确保loading状态一定会被重置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:36:17