Fetch的基本使用
[TOC]
1. 使用 fetch
1. 安装
npm install whatwg-fetch --save
import 'whatwg-fetch'
2. 基本使用
fetch 是全局变量 window 的一个方法,第一个参数是 URL
fetch('/some/url', {
method: 'get'
}).then(dunction(response) {
}).catch(function(err) {
});
1. 发送 get 请求
fetch('/some/url?name=zhangsan&password=123', {
method: 'get'
}).then(dunction(response) {
}).catch(function(err) {
});
数据拼接在url中
- method: HTTP 请求方法,默认为
GET
1. 发送 post 请求
fetch('/some/url', {
method: 'post',
headers: {
'Content-Type': 'application/x-www/form-urlencoded'
},
body:`?name=zhangsan&password=123'`,
mode:
}).then(dunction(response) {
}).catch(function(err) {
});
- body: HTTP 请求参数,数据放在
body
中 - headers: HTTP 请求头,可以设置头请求信息
- credentials(String):
- 默认为
omit
,忽略的意思,不带cookie; -
same-origin
,意思就是同源请求带cookie; -
include
,表示无论跨域还是同源请求都会带cookie
- 默认为
- mode:
-
same-origin:该模式是不允许跨域的,它需要遵守同源策略,否则浏览器会返回一个error告知不能跨域;其对应的response type为basic。
-
cors: 该模式支持跨域请求,顾名思义它是以CORS的形式跨域;当然该模式也可以同域请求不需要后端额外的CORS支持;其对应的response type为cors。
-
no-cors: 该模式用于跨域请求但是服务器不带CORS响应头,也就是服务端不支持CORS;这也是fetch的特殊跨域请求方式;其对应的response type为opaque。
-
3. 强制带Cookie
默认情况下,fetch 不会从服务端发送或接收任何 cookies,如果站点依赖于维护一个用户会话,则导致未经认证的请求(要发送 cookies,必须发送凭据头)。
2. Response 简介
Response 代表响应, fetch 的 then 方法接收一个 Response 实例。
// fetch 的 then 会传入一个 Response 对象
fetch('/')
.then(function(res) {
console.log('status: ', res);
});
Response 提供的方法如下:
-
clone() - 创建一个新的 Response 克隆对象.
-
error() - 返回一个新的,与网络错误相关的 Response 对象.
-
redirect() - 重定向,使用新的 URL 创建新的 response 对象..
-
arrayBuffer() - Returns a promise that resolves with an ArrayBuffer.
-
blob() - 返回一个 promise, resolves 是一个 Blob.
-
formData() - 返回一个 promise, resolves 是一个 FormData 对象.
-
json() - 返回一个 promise,resolves 是一个json对象
将原始数据转换成 JavaScript 对象,只是封装了 JSON.parse(jsonString).
-
text() - 返回一个 promise, resolves 是一个 USVString (text).