问题
i am trying to use the stack react redux and redux-saga and understand the minimal needed plumbing.
i did a github repo to reproduce the error that i got :
- https://github.com/kasra0/react-redux-saga-test.git
- running the app : npm run app
- url : http://localhost:3000/
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>
it comes from one of my sagas :
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.
thanks a lot for your help !
Kasra
回答1:
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'])
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
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
回答2:
Just another way to do without using call
method.
let res = yield call(fetch,fetch_url, {mode: 'no-cors'})
let json = yield res.json();
console.log(json)
Another way
const json = yield call([res, res.json]);
来源:https://stackoverflow.com/questions/47499340/cant-yield-json-response-from-server-with-redux-saga