最近用react实现一个响应式的新闻展示的应用,主要技术react + antdesign + fetch + react-router,新闻数据来自网上公共api,在用fetch请求api时报错,
  
跨域报错

原因是服务端没有设置响应header为Access-Control-Allow-Origin:*,因为是公共api无法从服务端解决问题,只能在前端跨域解决。使用fetch-jsonp可以实现跨域请求,github链接;

1. fetch的用法

  1. 安装
1
npm install fetch
  1. 用例
    GET方法:
1
2
3
4
5
6
7
8
fetch('/url/api?data1=xx&data2=xx&data3=xx,{
method: 'GET'
})
.then(response=>response.json())
.then(json=>{something handle...})
.catch(function(error) {
console.log('request failed', error)
});

POST方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var myFetchOptions = {
method: 'POST',
headers: {
'Access-Control-Allow-Origin':'',
'Content-Type': 'application/json'
},
body: JSON.stringify({
data1: 'xx',
data2: 'xx',
data3: 'xx'
})
};
fetch("url/api", myFetchOptions)
.then((response)=>response.json())
.then(json=>{something handle...})
.catch(function(error) {
console.log('request failed', error)
});

fetch用法采用ES6的promise写法,在上面的案例使用箭头函数,简化了函数的写法,包括参数和返回值,安装完fetch不用导入,可以直接使用,第一个参数为api,第二个参数为配置项,可设置请求头、请求模式、请求方法、请求参数等等,更多关于fetch高级用法请参考fetch的github文档。注意,报错图片中会提示把请求模式改为mode:'no-cors',用于不透明的服务,即我们只需要请求,不关注是否响应数据,即响应状态为0时,它不继续进行重定向数据请求,对于需要返回数据的请求操作是毫无意义,所以我们接下来更加关注跨域请求,获取数据。

2. fetch-jsonp的用法

  1. 安装
1
2
npm install fetch-jsonp

  1. 用例
    注意:JSONP只支持GET方法,与fetch-jsonp相同:
    用之前需要导入,不然会报错fetchJsonp未定义。
1
2
3
4
5
6
7
8
import fetchJsonp from'fetch-jsonp';

fetchJsonp('/uri/api?data1=xx&data2=xx&data3=xx)
.then(response=>response.json())
.then(json=>{something handle...})
.catch(function(error) {
console.log('request failed', error)
});

这里详细介绍这个response,这是请求api后响应(response)的相关数据,是一个Object,包括属性和主要的方法:

属性:

status (number) - HTTP响应状态码在100–599之间
statusText (String) - 服务器的状态文本
ok (boolean) - 如何HTTP状态码是2xx
headers (Headers) - 响应头
url (String) - 请求url

方法:

text() - 生成数据为文本字符串时
json() - 生成数据为json类型时
blob() - 生成数据为Blob
arrayBuffer() - 生成数据为ArrayBuffer
formData() - 生成可以被转发到另一个请求的FormData

其他方法:

clone()
Response.error()
Response.redirect()

fetch和fetchJsonp常见的用法就是这么简单,更多高级用法请参考github文档