无法使用 redux-saga 从服务器产生 json 响应 [英] Can't yield json response from server with redux-saga
问题描述
我正在尝试使用堆栈 react redux 和 redux-saga 并了解所需的最少管道.
i am trying to use the stack react redux and redux-saga and understand the minimal needed plumbing.
我做了一个 github repo 来重现我得到的错误:
i did a github repo to reproduce the error that i got :
- https://github.com/kasra0/react-redux-saga-test.git
- 运行应用程序:npm run app
- url : http://localhost:3000/
该应用程序由一个简单的组合框和一个按钮组成.从组合中选择一个值后,单击按钮会发送一个操作,该操作仅包含获取一些 json 数据.服务器收到正确的请求(基于选定的值),但在 let json = yield call([res, 'json']) 行.我收到错误:
the app consists of a simple combo box and a button. Once selecting a value from the combo, clicking the button dispatch an action that consists simply of fetching some json data . The server recieves the right request (based on the selected value) but at the line let json = yield call([res, 'json']). i got the error :
我从浏览器收到的错误消息:
the error message that i got from the browser :
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)
}
我在管道中做错了什么,但我找不到在哪里.
I did something wrong in the plumbing but i can't find where.
非常感谢您的帮助!
卡斯拉
推荐答案
从 redux-saga
的观点来看,所有代码都稍微正确——两个 promise 通过 call
顺序执行影响.
From redux-saga
viewpoint all code is slightly correct - two promises are been executed sequentially by call
effect.
let res = yield call(fetch,fetch_url, {mode: 'no-cors'})
let json = yield call([res, 'json'])
但是在 no-cors
模式下使用 fetch
意味着响应正文将无法从程序代码中获得,因为请求模式是 opaque
这样:https://fetch.spec.whatwg.org/#http-fetch一个>
But using fetch
in no-cors
mode meant than response body will not be available from program code, because request mode is opaque
in this way: https://fetch.spec.whatwg.org/#http-fetch
如果您想从不同来源获取信息,请使用 cors
模式和适当的 HTTP 标头,如 Access-Control-Allow-Origin
,更多信息请参见此处:
If you want to fetch information from different origin, use cors
mode with appropriate HTTP header like Access-Control-Allow-Origin
, more information see here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
这篇关于无法使用 redux-saga 从服务器产生 json 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!