Promise
之上设计,旧版本IE 彻底不支持,须借助 polyfill来兼容promise
对象,请求成功的数据返回到Responese回调中,请求失败的信息返回到 Request中。fetch
返回的promise
不会被标记为 reject
而会被标记为resolve
,好比状态码为 404,500.只有网络故障或请求被阻止时才被标记为reject
fetch('https://api.apiopen.top/musicDetails1') .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(myJson); //{code: 400, message: "404 Not Found", result: "https://api.apiopen.top/musicDetails1"} })
fetch
默认是不会从服务端发送接收或发送任何 cookie
,若是须要则必须设置 credentials,自 2017/8 起默认的credentials政策变动为same-originFirefox也在61.0b13中改变默认值method
: 请求使用的方法,如 GET、POST。javascript
headers
: 请求的头信息,形式为 Headers 的对象或包含 ByteString值的对象字面量。html
body
:
请求的 body
信息:
多是:
Blob( 表示一个不可变、原始数据的类文件对象)、
BufferSource
( 用于表示自身为ArrayBuffer或者TypedArray提供对象的对象ArrayBufferView。)、
FormData(表示表单数据的键值对的构造方式,通过它的数据可使用XMLHttpRequest.send()
方法送出,本接口和此方法都至关简单直接。若是送出时的编码类型被设为 "multipart/form-data",它会使用和表单同样的格式。)、
URLSearchParams (接口定义了一些实用的方法来处理 URL 的查询字符串)
或者 USVString
对象。
java
mode
: 请求的模式,如 cors、 no-cors
或者 same-origin
。git
credentials
: 请求的 credentials
,如 omit、same-origin
或者 include
。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 开始, 这个属性也能够接受 FederatedCredential 实例或是一个 PasswordCredential 实例。
5.1 若是须要跨域请求需设置为 "include"
5.2 若是只在同域内发送cookie 则设置为 "same-origin"
5.3 若是任何状况都不发送cookie 则设置为 "omit"es6
cache
: 请求的 cache
模式: default 、 no-store 、 reload 、 no-cache 、 force-cache
或者 only-if-cached
。github
redirect
: 可用的redirect
模式:follow
(自动重定向), error
(若是产生重定向将自动终止而且抛出一个错误), 或者manual
(手动处理重定向). 在Chrome中,Chrome 47以前的默认值是 follow
,从 Chrome 47开始是manual
。ajax
referrer
: 一个USVString 能够是 no-referrer、client
或一个URL
。默认是client
。json
referrerPolicy
:指定引用HTTP头的值。多是一个 no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
api
integrity
: 包括请求的 subresource integrity值 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。跨域
const Fetch = function (url,config){ if(typeof(config) !== 'object' || config === null) return throw `Config needs to pass an object type` let data = config || {} ; let {method = 'GET', param = null, mode = "cors", cache = "no-cache",headers = {'Access-Control-Allow-Origin': '*', 'content-type': 'application/json'}, redirect = "follow", credentials = "include", referrer = "no-referrer"} = data; /* // 传输 JSON 数据 需将 param 转换 JSON.stringify(param) //上传文件 需传输 formData 格式 let formData = new FormData() let fileField = document.querySelector("#myFile") formData.append('title',"My File") formData.append('fileField ',fileField .files[0]) */ return fetch(url,{ method:method.toUpperCase(), body:param, mode, cache, headers, redirect, credentials, }).then(res =>{ if(res.ok) return res.json() throw new Error("Network response fail:"+res.status) } ).catch(err=>console.error(err)) } Fetch('https://api.apiopen.top/musicDetails1',{credentials:'omit'}).then(res =>console.log(res)).catch(err=>console.error(err))
let content = "Hello World"; let myHeaders = new Headers(); myHeaders.append("Content-Type", "text/plain"); myHeaders.append("Content-Length", content.length.toString()); myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
let content = "Hello World"; let myHeaders = new Headers({ "Content-Type": "text/plain", "Content-Length": content.length.toString(), "X-Custom-Header": "ProcessThisImmediately", }); //获取和设置 console.log(myHeaders.has("Content-Type")); // true console.log(myHeaders.has("Set-Cookie")); // false myHeaders.set("Content-Type", "text/html"); myHeaders.append("X-Custom-Header", "AnotherValue"); console.log(myHeaders.get("Content-Length")); // 11 console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"] myHeaders.delete("X-Custom-Header"); console.log(myHeaders.getAll("X-Custom-Header")); // [ ]
若是使用了一个不合法的HTTP Header属性名,那么Headers的方法一般都抛出 TypeError 异常。若是不当心写入了一个不可写的属性,也会抛出一个 TypeError 异常。除此之外的状况,失败了并不抛出异常。
fetch(myRequest).then(function(response) { if(response.headers.get("content-type") === "application/json") { return response.json().then(function(json) { // process your JSON further }); } else { console.log("Oops, we haven't got JSON!"); } });
fetch
返回的对象if(this.fetch) { // run my fetch request here } else { // do something with XMLHttpRequest? }