无法使用 redux-saga 从服务器产生 json 响应

Can't yield json response from server with redux-saga

我正在尝试使用堆栈 react redux 和 redux-saga 并了解所需的最少管道。

我做了一个 github 回购来重现我得到的错误:

  1. https://github.com/kasra0/react-redux-saga-test.git
  2. 运行应用程序:npm 运行 应用程序
  3. url : http://localhost:3000/

该应用程序由一个简单的组合框和一个按钮组成。 从组合中选择一个值后,单击按钮将发送一个操作,该操作仅包括获取一些 json 数据。 服务器收到正确的请求(基于所选值),但在 let json = yield call([res, 'json']) 行。我收到错误:

我从浏览器收到的错误消息:

 index.js:2177 uncaught at equipments at equipments 
   at takeEvery 
   at _callee 
 SyntaxError: Unexpected end of input
 at runCallEffect (http://localhost:3000/static/js/bundle.js:59337:19)
 at runEffect (http://localhost:3000/static/js/bundle.js:59259:648)
 at next (http://localhost:3000/static/js/bundle.js:59139:9)
 at currCb (http://localhost:3000/static/js/bundle.js:59212:7)
 at <anonymous>

它来自我的一个传奇故事:

import {call,takeEvery,apply,take}  from 'redux-saga/effects'
import action_types                 from '../redux/actions/action_types'

let process_equipments = function* (...args){
    let {department} = args[0] 
    let fetch_url = `http://localhost:3001/equipments/${department}`
    console.log('fetch url : ',fetch_url)
    let res  =  yield call(fetch,fetch_url, {mode: 'no-cors'})
    let json =  yield call([res, 'json']) 
    // -> this is the line where something wrong happens
}

export function* equipments(){ 
    yield takeEvery(action_types.EQUIPMENTS,process_equipments)
}

我在管道上做错了,但我找不到哪里。

非常感谢您的帮助!

卡斯拉

redux-saga 的观点来看,所有代码都略微正确 - 两个承诺按 call 效果顺序执行。

let res  =  yield call(fetch,fetch_url, {mode: 'no-cors'})
let json =  yield call([res, 'json']) 

但是在 no-cors 模式下使用 fetch 意味着响应 body 将无法从程序代码中获得,因为请求模式是 opaque 这样: https://fetch.spec.whatwg.org/#http-fetch

如果您想从不同的来源获取信息,请使用 cors 模式和适当的 HTTP header,例如 Access-Control-Allow-Origin,更多信息请参见此处:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

另一种调用 .json() 而不使用 call 方法的方法。

let res  =  yield call(fetch,fetch_url, {mode: 'no-cors'})

// instead of const json =  yield call([res, res.json]);
let json =  yield res.json();

console.log(json)