Fetch API 提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应。它还提供了一个全局 fetch()方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。
不通过 XMLHttpRequest 实现
基本语法
fetch(url[,option])
示例
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
第一次返回Response对象,response.json()返回的是一个promise
POST请求
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('https://example.com', {
credentials: 'include'
})
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");
fetch('url',{headers:myHeaders})
in node.js
npm install node-fetch --save
const fetch = require('node-fetch');
fetch('https://www.xxx.com/machines')
.then(res => res.json())
.then(data => console.log(data));
await/async
async function goFetch() {
let response = await fetch('https://cp-api.zhgcloud.com/machines')
let data = await response.json()
console.log(data)
}
goFetch()
Tip:
当接收到一个代表错误的 HTTP 状态码时,从 fetch()返回的 Promise 不会被标记为 reject, 即使该 HTTP 响应的状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve (但是会将 resolve 的返回值的 ok 属性设置为 false ),仅当网络故障时或请求被阻止时,才会标记为 reject。所以关于状态码的错误需要自己封装。
fetch不能中断,没有 abort、terminate、onTimeout 或 cancel 方法