在调试 ant-design-pro 项目时里面使用 fetch 方法进行 api 请求
想通过保持与 ant-design-pro 一致的api请求方式进行获取自己系统中的数据,
请求代码如下:
fetch('http://www.demo.com:9001/api/Tbox/GetAllVehicleFactoryWithUploadDateTimeDesc').then(res => {
console.log(res);
return res.json();
}).then(json => {
console.log('获取的结果', json);
return json;
}).catch(err => {
console.log('请求错误', err);
})
执行结果:
Access to fetch at ‘http://www.demo.com:9001/api/Tbox/GetAllVehicleFactoryWithUploadDateTimeDesc’ from origin ‘http://localhost:8000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
VM20690:8 请求错误 TypeError: Failed to fetch
经查资料分析,浏览器只允许请求当前域的资源,而对其他域的资源表示不信任。
cors是"Cross-Origin Resource Sharing"的简称,是实现跨域的一种方式,相对于其他跨域方式,比较灵活,而且不限制发请求使用的method,以下从几种情况分析cors使用。
那怎么才算跨域呢?
1. 前端代码
添加请求参数, mode : ‘cors’
fetch('http://www.demo.com:9001/api/Tbox/GetAllVehicleFactoryWithUploadDateTimeDesc',{
method: 'GET',
mode: 'cors'
}).then(res => {
console.log(res);
return res.json();
}).then(json => {
console.log('获取的结果', json);
return json;
}).catch(err => {
console.log('请求错误', err);
})
2. 后端设置
(1)以IIS为示例
设置HTTP响应标头
Access-Control-Allow-Credentials : true
Access-Control-Allow-Headers : *
Access-Control-Allow-Methods : PUT,POST,GET,DELETE,OPTIONS
Access-Control-Allow-Origin : http://localhost:8000
说明:
(2)在Response的Headers中设置HTTP响应标头
如下以 C# Web Api 为示例
HttpResponseMessage result = request.CreateResponse(HttpStatusCode.OK, content);
result.Headers.Add("Access-Control-Allow-Credentials", "true");
result.Headers.Add("Access-Control-Allow-Headers", "*");
result.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
result.Headers.Add("Access-Control-Allow-Origin", "http://localhost:8000");
request跨域头部介绍
response头部