1. fetch基本使用
//基本用法
fetch('http://localhost:3000/data')
.then(function (data) {
//text() 方法属于fetchAPI的一部分,他返回一个Promise实例对象,用于获取后台返回的数据
return data.text();
}).then(function (data) {
//注意这里才是最终数据
console.log(data);
})
2. fetch请求参数
1.常用配置选项
method
(String) :HTTP请求方式,默认为getbody
(String) :HTTP的请求参数headers
(Object):HTTP的请求头,默认为{}
2.get请求参数的参数传递
fetch('http://localhost:3000/books/456', {
method: 'get'
})
.then(function (data) {
return data.text();
}).then(function (data) {
console.log(data);
})
3.delete方式传参
fetch('http://localhost:3000/books/789', {
method: 'delete'
})
.then(function (data) {
return data.text();
}).then(function (data) {
console.log(data);
})
4.post请求方式传参
post和put请求:
- 需要在
body
中传递参数- 需要指定
headers
fetch('http://localhost:3000/books', {
method: 'post',
body: 'uname=lisi&pwd=123',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})
.then(function (data) {
return data.text();
}).then(function (data) {
console.log(data);
})
5.put请求方式传参
fetch('http://localhost:3000/books/123', {
method: 'put',
body: 'uname=lisi&pwd=123',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(function (data) {
return data.text();
}).then(function (data) {
console.log(data)
})
3. fetch响应结果
响应数据格式
text()
:将返回处理成字符串类型json()
:返回结果和JSON.parse(responseText)
一样