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中改变默认值
设置项工具,包罗所有对请求的设置
1.method: 请求使用的方式,如 GET、POST。
2.headers: 请求的头信息,形式为 Headers 的工具或包罗 ByteString值的工具字面量。
3.body:请求的 body信息可能是:
Blob( 示意一个不可变、原始数据的类文件工具)、
BufferSource ( 用于示意自身为ArrayBuffer或者TypedArray提供工具的工具ArrayBufferView。)、
FormData(示意表单数据的键值对的组织方式,经由它的数据可以使用XMLHttpRequest.send() 方式送出,本接口和此方式都相当简朴直接。若是送出时的编码类型被设为 "multipart/form-data",它会使用和表单一样的花样。)、
URLSearchParams (接口界说了一些适用的方式来处置 URL 的查询字符串)或者 USVString 工具。
注重GET 或HEAD方式的请求不能包罗 body 信息。
4.mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
5.credentials: 请求的 credentials,如 omit、same-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 最先, 这个属性也可以接受 FederatedCredential 实例或是一个PasswordCredential 实例。
若是需要跨域请求需设置为 "include"
若是只在同域内发送cookie 则设置为 "same-origin"
若是任何情形都不发送cookie 则设置为 "omit"
6.cache: 请求的 cache 模式: default 、 no-store 、 reload 、 no-cache 、 force-cache 或者 only-if-cached 。
7.redirect: 可用的redirect 模式:follow(自动重定向), error (若是发生重定向将自动终止而且抛出一个错误), 或者manual (手动处置重定向). 在Chrome中,Chrome 47之前的默认值是 follow,从 Chrome 47最先是manual。
8.referrer: 一个USVString 可以是 no-referrer、client或一个URL。默认是client。
9.referrerPolicy:指定引用HTTP头的值。可能是一个 no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
10.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))
建立一个 headers 工具,一个 headers 工具是一个简朴的多名值对:
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!");
}
});
if(this.fetch) {
// run my fetch request here
} else {
// do something with XMLHttpRequest?
}
1.阿里云: 本站现在使用的是阿里云主机,平安/可靠/稳固。点击领取2000米代金券、领会最新阿里云产物的种种优惠流动点击进入
2.腾讯云: 提供云服务器、云数据库、云存储、视频与CDN、域名等服务。腾讯云各种产物的最新流动,优惠券领取点击进入
3.广告同盟: 整理了现在主流的广告同盟平台,若是你有流量,可以作为参考选择适合你的平台点击进入
链接: http://www.fly63.com/article/detial/3890