fetch('http://localhost:3000/getRencentJob', {
method: 'GET', //请求方法是get
mode:'cors', //模式:跨域请求 还有no-cors不跨域请求
headers: {//请求头
'Accept': 'application/json', //接受的数据格式是json
'Content-Type': 'application/json', // 发送的格式是json
},
}).then(function (res) { //第一个then返回response
console.log("----------------------JSON QUERY : res.status:"+res.status);
if(res.status === 200){
return res.json() //响应体 等价于 JSON.parse(responseText)一样
}
}).then(function (json) { //第二个then的参数 接受的就是前一个then返回的对象 也就是res.json()
context.commit('setJson', json);
})
Fetch使用说明
fetch(url, options).then(function(response) {
// handle HTTP response
}, function(error) {
// handle network error
})
说明:
a. fetch api返回的是一个promise对象
b.Options:
method(String): HTTP请求方法,默认为GET
body(String): HTTP的请求参数
headers(Object): HTTP的请求头,默认为{}
credentials(String): 默认为omit,忽略的意思,也就是不带cookie;还有两个参数,same-origin,意思就是同源请求带cookie;include,表示无论跨域还是同源请求都会带cookie
c.第一个then函数里面处理的是response的格式,这里的response具体如下:
status(number): HTTP返回的状态码,范围在100-599之间
statusText(String): 服务器返回的状态文字描述,例如Unauthorized,上图中返回的是Ok
ok(Boolean): 如果状态码是以2开头的,则为true
headers: HTTP请求返回头
body: 返回体,这里有处理返回体的一些方法
text(): 将返回体处理成字符串类型
json(): 返回结果和 JSON.parse(responseText)一样
blob(): 返回一个Blob,Blob对象是一个不可更改的类文件的二进制数据
arrayBuffer()
formData()