小傻 2019-06-29
Fetch 提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应。它还提供了一个全局 fetch()方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。
这种功能以前是使用 XMLHttpRequest实现的,Fetch提供了一个更好的替代方法
Fetch API 是基于 Promise 设计,使用了Promises 来处理结果/回调。旧浏览器不支持 Promise,需要使用 polyfill es6-promise 。
fetch("http://192.168.43.169:8099/someInfo",{
method: 'post',
})
.then(res=>{
console.log(response) // 包含响应结果的promise,只是一个 HTTP 响应,而不是真的JSON
return response.json();
})
.then(res=>{
console.log(res) //js格式的json对象
})async await实现更方便
const fetchRequest = async () => {
let response = await fetch("http://192.168.43.169:8099/teacher/resume", {
method: 'post',
})
let data = await response.json()
console.log(data); //js格式的json对象
}
fetchRequest()属性:
方法:处理包含返回结果的promise对象的数据
例如 response.json()
处理包含json结果的promise对象
创建request对象
request = new Request()
属性:
let request = new Request("http://192.168.43.169:8099/teacher/resume",{
method: 'post',
headers: new Headers({
'Content-Type': 'text/plain'
})
})
fetch(request)
.then(res=>{
console.log(res);
return res.json();
})
.then(res=>{
console.log(res)
})创建header对象
let headers = new Headers();
headers方法:
设置header通过属性或者方法都可以
属性形式:传一个多维数组或者对象字面量
Header = new Headers({
"Content-Type": "text/plain",
"Content-Length": content.length.toString(),
"X-Custom-Header": "ProcessThisImmediately",
});方法形式:
var Header = new Headers();
Header.append("Content-Type", "text/plain");
Header.append("Content-Length", content.length.toString());
Header.append("X-Custom-Header", "ProcessThisImmediately");