由于此API请求,我在过去的几分钟里一直在敲打我的头……
我有以下代码:
佐贺
export function * registerFlow () {
while (true) {
const request = yield take(authTypes.SIGNUP_REQUEST)
console.log('authSaga request', request)
let response = yield call(authApi.register, request.payload)
console.log('authSaga response', response)
if (response.error) {
return yield put({ type: authTypes.SIGNUP_FAILURE, response })
}
yield put({ type: authTypes.SIGNUP_SUCCESS, response })
}
}
API请求:
// Inject fetch polyfill if fetch is unsuported
if (!window.fetch) { const fetch = require('whatwg-fetch') }
const authApi = {
register (userData) {
fetch(`http://localhost/api/auth/local/register`, {
method : 'POST',
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
body : JSON.stringify({
name : userData.name,
email : userData.email,
password : userData.password
})
})
.then(statusHelper)
.then(response => response.json())
.catch(error => error)
.then(data => data)
}
}
function statusHelper (response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
export default authApi
API请求确实返回有效对象,但是Saga调用的返回始终未定义。谁能引导我到错误的地方?
提前致谢!
最好的祝福,
布鲁诺
最佳答案
您忘记对函数中的 promise 进行return
编码。做了
const authApi = {
register (userData) {
return fetch(`http://localhost/api/auth/local/register`, {
// ^^^^^^
method : 'POST',
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
body : JSON.stringify({
name : userData.name,
email : userData.email,
password : userData.password
})
})
.then(statusHelper)
.then(response => response.json());
}
};