求助一个react使用fetch请求数据实例,接口有跨域问题且后台没有设置。
求一个fetch实例
//ES5 写法
clickBtn(e){
let self=this;//缓存this对象
fetch('http://192.168.1.96:8090/speakit/menu/getMenu')
.then(function(response){
return (response.json());
}).then(function(data){
self.setState({
menu:data.menus
})
})
}
//ES6 写法
clickBtn02(e){
fetch('http://192.168.1.96:8090/speakit/menu/getMenu')
.then(response=>response.json())
.then(data=>{
console.log(data);
this.setState({
menu:data.menus
})
})
}
mumuyu65
#8
先让后台允许你进行跨域请求,不然你就算使用了jsonp也是无法请求到数据的。跨域请求的前提是后台允许进行跨域请求。
我这里有个实例你可以参考一下:
import ‘whatwg-fetch’
export function ajaxApi(url,option = {}){
let params = {},
method = option.method || ‘get’,
data = option.data || {};
switch(method){
case 'get':
url = url+(data ? '?' +formDataCode(data) : '');
break;
case 'post':
option.headers = {};
option.body = formDataCode(data);
option.headers['Content-Type' ] = "application/x-www-form-urlencoded;charset=UTF-8";
break;
default:
console.log("ajax..");
}
return fetch(url,option).then(callback).catch(errHandle);
}
//创建修改参数格式的方法,改成提交的Form Data格式
function formDataCode(data){
let str = ‘’;
for(let i in data){
if(data.hasOwnProperty(i)){
str = str + i +"=" +data[i] + '&';
}
}
return str ? str.substring(0,str.length - 1) : '';
}
//创建fetch中then方法的回调
function callback(res){
return res.json().then(response =>{
console.log(‘服务器的响应’,response);
if(!response){
throw “服务器返回参数错误”
}else if(response.errcode == 40001){
throw “token失效,请刷新页面”
}else if(response.errcode == -1){
return response
}
return response;
})
}
//创建容错方法
function errHandle(res){
if(res.errcode == -1){
alert(res.errmsg)
}
}