fetch如何发起请求
fetch('/https://xxxx.xxx').then((data)=>{
//text()属于feych的API的一部分,返回的是一个Promise实例对象,用于获取后台返回的数据
return data.text();
}.then(data => {
console.log(data);
}))
- fetch请求携带参数
- method(String):HTTP请求方法,默认为GET(GET、POST、PUT、DELETE)
- body(String):HTTP的请求参数
- headers(Object):HTTP的请求头,默认{}
- GET请求方式传递参数
fetch('/https://xxxx.xxx/1234',{
methods: 'GET'
})
.then(data => {
return data.text();
}.then(res => {
//最终的数据
console.log(res);
}));
fetch('/https://xxxx.xxx/1234',{
methods: 'DELETE'
})
.then(data => {
return data.text();
}.then(res => {
//最终的数据
console.log(res);
}));
fetch('/https://xxxx.xxx',{
methods: 'POST',
//用于传递实际参数
body : 'username=xxx&pwd=1234',
//进行配置
headers:{
'Content-Type' : 'application/x-www-form-urlencode'
}
})
.then(data => {
return data.text();
}.then(res => {
console.log(res);
}));
fench请求返回值处理
fetch('/https://xxxx.xxx/1234',{
methods: 'GET'
})
.then(data => {
return data.text();
}.then(res => {
//最终的数据
console.log(res);
}));
- json():返回结果和JSON.parse()样
fetch('/https://xxxx.xxx/1234',{
methods: 'GET'
})
.then(data => {
return data.json();
}.then(res => {
//最终的数据
console.log(res);
}));