引言
基于fetch API,前后端交互不再依赖第三方包。
以下是自己项目中使用fetch方法进行交互。
get
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40const fetchGET = ( url, params = {} ) => {
let headerObj = {
credentials: 'include', // 设置跨域时,也可以发送cookie
method: 'GET',
};
let urlObj = url;
if ( JSON.stringify( params ) !== '{}' ) {
let temp = [];
const len = Object.keys( params ).length;
Object.keys( params ).map( ( v, i ) => {
temp.push( `${v}=${params[ v ]}` );
if ( i + 1 < len ) {
temp.push( '&' );
}
} );
urlObj = `${url}?${temp.join( '' )}`;
}
return fetch( `${urlObj}`, headerObj )
.then( ( response ) => {
return response.json();
} )
.then( ( data ) => {
if ( data.status < 0 ) {
Message.error( data.msg || '请求失败' );
} else if (data.status === 1){
data.msg && Message.success( data.msg );
}
return data;
} )
.catch( ( e ) => {
return {
msg: '请求失败'
}
} )
}post file
使用formData进行文件提交。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25const fetchFILE = ( url, params = {} ) => {
let headerObj = {
credentials: 'include',
method: 'POST'
};
return fetch( url, {
...headerObj,
body: params
} ).then( function ( response ) {
return response.json();
} ).then(data => {
if ( data.status < 0 ) {
Message.error( data.msg || '请求失败' );
} else if (data.status === 1){
data.msg && Message.success( data.msg );
}
return data;
}).catch( function ( e ) {
return {
msg: '请求失败'
}
} )
}post
1 | const fetchPOST = ( url, params = {}, header = {} ) => { |