title: 二、fetch中的基础语法
categories:
- Ajax异步交互与跨域访问
- Axios
tags: - fetch
date: 2020-08-23 19:56:01
highlight_shrink: false
参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
fetch概念
fetch不是Ajax,它诞生的目的是为了代替Ajax,它是js中内置的API。
基于fetch可以实现客户端和服务端的信息通信
由于fetch是2018年提出,因此存在浏览器兼容问题。
fetch('https://v1.hitokoto.cn', {
method: 'GET',
}).then(result => {
console.log(result);
})
fetch('https://v1.hitokoto.cn', {
method: 'POST',
body: 'c=b',
headers: {
'Content-Type': 'x-www-form-urlcoded'
},
credentials: 'include'
}).then(result => {
console.log(result);
})
注意问题
- GET/HEAD等请求不能设置body
- 不管服务器返回的状态是多少,fetch都不认为是失败。并且会执行then方法。
返回结果
通过回调函数并不能直接获得响应结果。其返回结果为一个对象。
-
headers
包含响应头信息
-
redirected
是否重定向
-
status
响应码
-
statusText
响应文本
-
type
basic/cors
-
url
请求地址
通过其提供的方法获取真正数据。