资源翻译于https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#Body
fetch是比XMLHttpRequest更好的替代方案,
fetch的api比XMLHttpRequest更加的细致,能够实现更多的功能
譬如说发送的报文,fetch大量的api可以让我们对发送的内容进行操控及自定义请求对象
例 基本的fetch请求
fetch('https://www.baidu.com/movies.json')
.then(function(res) {
return res.json;
})
.then(function(myjson) {
console.log(myjson);
});
fetch指定传输的方法 GET/POST
fetch('https://www.baidu.com/search/error.html', {
method: 'GET'
//method: 'POST'
});
fetch传参使用的方法
GET
fetch('https://www.baidu.com/search/error.html?a=1&b=2', { // 在URL中写上传递的参数
method: 'GET'
});
POST
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html', {
method: 'POST',
body: new URLSearchParams([["foo", 1],["bar", 2]]).toString() // 这里是请求对象
})
以上就是fetch常见的使用方式,但是他的优点我还没有展示 马上
fetch支持的请求参数
//以post方法举例
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) {
// Default options are marked with *
return fetch(url, {
//将data转化为string
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'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()) // parses response to JSON
}
在里面我们可以设置报文的内部结构 包括头部 Content-Type等也可以使用cors去避免跨域的等等问题、重定向等等
fetch出现的上传json和上传文件等
上传文件
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
上传json
var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
fetch的注意点:当出现网络故障时promise会reject并带上TypeError的对象
但是当出现404等状况时不会变成reject只会改变resolved中的 Response.ok的值为false
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
自定义请求对象除了传给 fetch()
一个资源的地址,你还可以通过使用 Request()
构造函数来创建一个 request 对象,然后再作为参数传给 fetch()
var myHeaders = new Headers();
var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' };
var myRequest = new Request('flowers.jpg', myInit);
fetch(myRequest).then(function(response) {
return response.blob();
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
还有一些常用的接口 Header、response、body等