ReactJS中在saga调用axios发送请求后如何从Promise获取返回结果
你遇到的情况是正常的,axios.post() 默认返回Promise实例,你可以通过以下方式获取接口实际返回数据:
方案1:Redux Saga 环境推荐写法(优先使用)
在Saga中不要直接调用异步请求方法,使用Saga内置的call Effect来执行异步函数,Saga会自动等待Promise完成并返回结果,这是Saga的标准异步处理方式:
// 先从redux-saga/effects导入call import { call } from 'redux-saga/effects' // 你的Saga生成器函数 function* authSaga(action) { try { // call第一个参数是要执行的异步方法,后续参数是传入该方法的入参 const response = yield call( client.post, 'api/JwtAuth/GenerateToken', { UserName: action.username, Password: action.password } ) // 接口返回的实际数据存储在response.data中 console.log('返回数据:', response.data) // 后续可结合put Effect将数据存入Redux存储 } catch (error) { // 捕获请求异常,比如鉴权失败、服务端报错等 console.error('请求失败:', error) } }
方案2:原生Promise写法(不推荐在Saga中使用)
如果不使用Saga的Effect能力,也可以通过Promise的.then()回调获取结果:
client.post('api/JwtAuth/GenerateToken', { UserName: action.username, Password: action.password }).then(response => { console.log('返回数据:', response.data) }).catch(error => { console.error('请求失败:', error) })
额外注意
你封装axios实例时header字段写法有误,标准的内容类型键名是Content-Type,建议修正避免部分后端无法正常解析请求:
const client = axios.create({ baseURL: 'https://localhost:5001/', timeout: 600000000000, headers: { 'Content-Type': 'application/json' } })
内容的提问来源于stack exchange,提问作者GettingStarted
相关产品推荐
相关产品推荐

