前端开发中,向服务器请求数据通常用三种:XMLHttpRequest、fetch、jQuery的ajax
XMLHttpRequest、fetch是浏览器的原生API,fetch在IE和低版本的浏览器支持不友好
jQuery的ajax其实就是对XMLHttpRequest的封装实现
建议在项目中引用第三方封装好的,以避免有些网站无法工作 fetch github
step1: yarn add whatwg-fetch
step2: import {fetch as fetchPolyfill} from 'whatwg-fetch'
step3: fetchPolyfill(api)
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})
简单的使用:
fetch(url, options).then(function(response) {
// handle HTTP response
}, function(error) {
// handle network error
})
全面使用:
fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin"
}).then(function(response) {
response.status //=> number 100–599
response.statusText //=> String
response.headers //=> Headers
response.url //=> String
return response.text()
}, function(error) {
error.message //=> String
})
参数解释:
url: 请求的地址
options: (请求配置)
method: HTTP请求方法,默认为GET
body: HTTP的请求参数
headers: HTTP的请求头,默认为{}
credentials: 默认为omit,忽略的意思,也就是不带cookie;还有两个参数,same-origin,意思就是同源请求带cookie;include,表示无论跨域还是同源请求都会带cookie
ps: body这里做一些解释说明,body可接收的类型有如下几种:String、URLSearchParams、FormData、Blob、ArrayBuffer、TypedArray、DataView
其他数据结构需要预先编码为上述类型之一。例如,JSON.stringify(data)
可用于将数据结构序列化为JSON字符串。
请注意,HTTP服务器通常要求使用正文发布的请求也通过Content-Type
请求标头指定其类型。
response:
Response表示来自服务器的HTTP响应。通常,Response不是手动构造的,但可作为已解析的promise回调的参数。
属性:
status (number) - 100-599范围内的HTTP响应代码
statusText (字符串) - 服务器报告的状态文本,例如“未授权”
ok(布尔值) - 如果status是HTTP 2xx则为真
headers(标题)
url (串)
方法:访问响应主体的每个方法都返回一个Promise,当关联的数据类型准备好时,它将被解析。
text() - 将响应文本生成为String
json() - 产生结果 JSON.parse(responseText)
blob()- 产生一个Blob
arrayBuffer()- 产生一个ArrayBuffer
formData()- 产生可以转发到另一个请求的FormData
以下代码是在实际开发中自己封装的一个方法
// 这里摄者一些请求公用的header
function cfg() {
const token = Token ? `Bearer ${Token}` : '';
const header = {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: token,
Uuid: DeviceId,
};
return header;
}
export default class HTTP {
static get(url, params) {
if (params) {
const paramsArray = [];
// 拼接参数
Object.keys(params).forEach(key => paramsArray.push(`${key}=${params[key]}`));
if (url.search(/\?/) === -1) {
url += `?${paramsArray.join('&')}`;
} else {
url += `&${paramsArray.join('&')}`;
}
}
// fetch请求
return fetch(url, {
method: 'GET',
headers: cfg(),
})
.then(response => response.json())
.then(responseJson => responseJson)
.catch((error) => {
console.error(error);
});
}
static post(url, params) {
// fetch请求
return fetch(url, {
method: 'POST',
headers: cfg(),
// body: params,
body: JSON.stringify(params),
})
.then(response => response.json())
.then(responseJson => responseJson)
.catch((error) => {
console.log(`error = ${error}`);
});
}
static file(url, data) {
const photo = { uri: data };
const formdata = new FormData();
formdata.append('product', { uri: photo.uri, name: 'image.jpg', type: 'multipart/form-data' });
return fetch(url, {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formdata,
})
.then(response => response.json())
.then((responseJson) => {
console.log(responseJson);
console.log('image uploaded');
return responseJson;
})
.catch((err) => {
console.log(err);
});
// })
}
static put(url, params) {
// fetch请求
return fetch(url, {
method: 'PUT',
headers: cfg(),
// body: params,
body: JSON.stringify(params),
})
.then(response => response.json())
.then(responseJson => responseJson)
.catch((error) => {
console.log(`error = ${error}`);
});
}
static delete(url) {
// fetch请求
return fetch(url, {
method: 'DELETE',
headers: cfg(),
// body: params,
// body: JSON.stringify(params),
})
.then(response => response.json())
.then(responseJson => responseJson)
.catch((error) => {
console.log(`error = ${error}`);
});
}
}
调用
import $ from '../utils/https';
export function getMusic(params) {
try {
return $.get(`${HOST}/videos`, params);
} catch (error) {
console.error(error);
}
}
// 实际页面调用
async handleFetchdata() {
const datas = await getMusic()
console.log(datas)
}