3

由于这个 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 调用的返回始终是未定义的。谁能指导我到哪里错了?

提前致谢!

此致,

布鲁诺

4

1 回答 1

6

你忘记了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());
  }
};
于 2016-09-30T01:41:36.180 回答