首先不得不吐槽一下fetch的response机制了,真的太麻烦了,当我快放弃的时候,才真正懂得怎么用
axios使用特别简单
axios("http://xxx/xxx.json?a=123'").then((r)=>{
console.log(r)//这里的r是响应结果
})
但是axios不支持jsonp就比较恶心了,不过我们可以引入jsonp模块,详细使用前面blog或github和npm用法
另外不建议使用jq进行ajax,毕竟太大了。
而fetch感觉是上了一个档次一样,他与axios的区别是他的response是一个综合各种方法的对象,并不是请求的数据,
我就犯了这样的错误,搞得我都想放弃fetch了
不过感觉机制还是蛮不错的,返回的是一个未处理的方法集合,我们可以通过这些方法得到我们想要的数据类型
如果我们想要json格式,就执行response.json(),如果我们想要字符串就response.text()
而且这些函数是一个promise,想要后台的数据需要.then才可以
例:fetch('http://xxx/xxx.json?a=123').then(res => {
res.json().then((r)=>{//或者res.text() console.log(r)//这里就是处理完的后台返回的json数据 })
})
另外可以引入fetch-jsonp,即支持fetch也支持fetchJsonp方法
fetchJsonp(
'
https://sug.so.360.cn/suggest?word=c
')
.
then (
function
(
r
) {
//fetchJsonp
console
.
log(
r)
r
.
json()
.
then(
function
(
data
){
console
.
log(
data)
;
})
;
})
不过这样也是一个回调函数,推荐以下的方法(使用return的方式)
1. 请求 json
另外jsonp只支持json,不支持字符串text
fetchJsonp(
'
https://sug.so.360.cn/suggest?word=c
')
.
then (
function
(
r
) {
//fetchJsonp
return
r
.
json()
})
.
then(
function
(
data
){
console
.
log(
data)
;//后台请求的数据
})
;
fetch('http://xxx/xxx.json?a=123').then(res => {
return res.json();//这是一个promise
}).then(res => {
console.log(res);//向后台请求的数据
})
- 1
- 2
- 3
- 4
- 5
2. 请求文本
fetch('/xxx/page').then(res => {
return res.text();
}).then(res => {
console.log(res);
})
- 1
- 2
- 3
- 4
- 5
3. 发送普通 json 数据
fetch('/xxx', {
method: 'post',
body: JSON.stringify({
username: '',
password: ''
})
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
4. 发送form 表单数据
var form = document.querySelector('form');
fetch('/xxx', {
method: 'post',
body: new FormData(form)
});
- 1
- 2
- 3
- 4
- 5
5. 获取图片
fetch('/xxx').then(res => {
return res.blob();
}).then(res => {
document.querySelector('img').src = URL.createObjectURL(imageBlob);
})
- 1
- 2
- 3
- 4
- 5
6. 上传
var file = document.querySelector('.file')
var data = new FormData()
data.append('file', file.files[0])
fetch('/xxx', {
method: 'POST',
body: data
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
封装
require('es6-promise').polyfill();
require('isomorphic-fetch');
export default function request(method, url, body) {
method = method.toUpperCase();
if (method === 'GET') {
body = undefined;
} else {
body = body && JSON.stringify(body);
}
return fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body
}).then((res) => {
if (res.status >= 200 && res.status < 300) {
return res;
} else {
return Promise.reject('请求失败!');
}
})
}
export const get = path => request('GET', path);
export const post = (path, body) => request('POST', path, body);
export const put = (path, body) => request('PUT', path, body);
export const del = (path, body) => request('DELETE', path, body);