fetch
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
fetch还接受Request实例对象:
https://developer.mozilla.org/zh-CN/docs/Web/API/Request/Request
postData('http://example.com/answer', {answer: 42})
.then(data => console.log(data)) // JSON from `response.json()` call
.catch(error => console.error(error))
function postData(url, data) {
return fetch(url, {
body: JSON.stringify(data), // 需要验证header的 Content-Type
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', //同源发送cookie, include, same-origin, *omit
headers: {
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()) // 将response数据 转为 JSON
上述代码中
{
headers:new Headers({});//见下方
body:{},//body可以是一下任意类型
/**
ArrayBuffer
ArrayBufferView(Uint8Array等)
Blob / File
string
URLSearchParams
FormData
*/
/**
//对应上面的类型,response有以下方法
arrayBuffer()
blob()
json()
text()
formData()
*/
}
//返回对象
Response.status — 整数(默认值为200) 为response的状态码.
Response.statusText — 字符串(默认值为"OK"), 该值与HTTP状态码消息对应.
Response.ok — 如上所示, 该属性是来检查response的状态是否在200 - 299(包括200, 299)
new URLSearchParams()
var paramsString = "q=URLUtils.searchParams&topic=api";//可以是对象
var searchParams = new URLSearchParams(paramsString);
for (let p of searchParams) {
console.log(p);
}
searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === ""; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"
new Headers()
如果使用了一个不合法的HTTP Header属性名,那么Headers的方法通常都抛出 TypeError 异常。如果不小心写入了一个不可写的属性,也会抛出一个 TypeError 异常。
https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers
var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
//也可以传一个多维数组或者对象字面量:
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")); // [ ]
网友评论