http 状态码和响应头
fetch('/api/user')
.then(res => res.json())
.then(res=>{
console.log(res)
})
async function fetchFunction() {
let response = await fetch('/api/user')
let body = await response.json()
return body
}
res => res.json() 用某个方法(json())将处理响应对象(可读流),获取响应体。
response 为响应对象 Response
- 它的 status 属性为状态码
- ok 属性(在status 在200~299之间为true,其他情况下为false)
- headers 属性是 Headers 对象,为响应头。有get(), has() 等方法,而且 http 的头部名称是不区分大小写的
Headers 对象是一个可迭代对象,可以使用 for...of 进行遍历
fetch 只要一收到http状态码和响应头就会resolve Promise,但此时还有收到完整的响应体。但是已经可以在第二步检查响应头了。
设置请求参数
请求参数可以以名 / 值的形式写在 url 后,可以通过 URL 和 URLParams 类构建 url。
async function fetchFunction(myName) {
let url = new URL('/api/user')
url.searchParams.set('name',myName)
let response = await fetch(url)
// ...
}
设置请求头
let authHeaders = new Headers()
authHeaders.set('Authorization', `Basic xxxx`)
fetch('/api/user', {headers: authHeaders})
//.then...
解析响应体
- json()
- text()
- formData() 当Response响应体是以'mutipart/form-data'格式编码的,使用该方法。不过,这种方法常用于向服务器发送post请求中,在服务器响应中不常见
指定请求方法和请求体
fetch('/api/user', {
method: 'POST',
headers: new Headers({'Content-Type': 'application/json'}),
body: 'hello world'
})