react 用fetch跨域请求,看控制台,是成功拿到数据,但是程序里返回的确是error
我是用dva框架,用fetch跨域请求。是成功拿到数据,但是程序里返回的确是error,不知错在哪里,望指教
1.看了下控制台,是成功拿到数据。如图:
打印了下返回结果,返回的确是error,如图:
2.代码如下:
import fetch from 'dva/fetch';
function parseJSON(response) {
return response.json();
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
export default function request(url, options,transform) {
const headers= {
'Accept': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials': true
};
const parmas=Object.assign(headers,options,{credentials: 'include'});
return fetch(url,parmas)
.then(checkStatus)
.then(parseJSON)
.then(data => {
if(transform instanceof Function){
return transform(data);
}
return data;
})
}
3.发起请求的地方:
effects: {
*queryUser ({payload}, {call, put}) {
const data = yield call(Services.userInfo, parse(payload));
console.log(data);
if (data.success) {
}else{
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fetch 的 问题 是因为 代理配置出错了,proxy要与env同级
fetch 部分只需要加上 (credentials: 'include'允许带上cookie),其他没什么特别
这些头是服务端返回的,不是请求头,先删掉这个在测试下
开发环境需要配置
proxy
,将跨域的地址代理出去。eg:
生产环境也需要配置
proxy
。如nginx
的配置,通过pass_proxy
代理出去。