react I don't know if there is, but there should be. The axios, used by vue can use the returned http status code to make related jumps
does every interface call XMLHttpRequest directly?
it is recommended that XMLHttpRequest be encapsulated as an ajax method and provided to the calling interface. In this ajax method, the status code of the returned body json is judged and redirected
add a response interceptor with axios, for example:
axios.interceptors.response.use(response => {
//
if (response.status && response.status == 200 && response.data.status == 'error') {
return;
}
return response;
}, err => {
if (err && err.response) {
switch (err.response.status) {
case 400:
err.message = ''
break;
case 401:
err.message = ''
break;
case 403:
err.message = ''
break;
case 404:
err.message = ','
break;
case 405:
err.message = ''
break;
case 408:
err.message = ''
break;
case 500:
err.message = ''
break;
case 501:
err.message = ''
break;
case 502:
err.message = ''
break;
case 503:
err.message = ''
break;
case 504:
err.message = ''
break;
case 505:
err.message = 'http'
break;
default:
err.message = '' + err.response.status
}
}
else {
err.message = ""
}
return Promise.resolve(err.response)
})
want to see the details of axios: https://www.kancloud.cn/yunye.
you can encapsulate the request method yourself, and then set the intercept.
// ajax
$(document).ajaxComplete((event, xhr, settings) => {
if (xhr.status === 200) {
if (settings.dataType === 'json' && xhr.responseJSON !== void 0) {
let result = xhr.responseJSON;
if (2001 === result.code) {
// session
global.location.href = "/main-login.html";
}
}
} else if (xhr.status === 401) {} else {
global.location.href = "/main-login.html";
}
});
export default function(options) {
const defaultOptions = {
dataType: 'json',
cache: true,
jsonp: 'callback'
};
options.data = processRequest(options);
//url
options.url = options.url;
options.headers = {
"Accept": "application/json",
"Content-Type": "application/json"
};
return $.ajax({...defaultOptions, ...options }).then(processResponse);
};
//
function processRequest(r) {
const str = r.data || {};
if ('get' == r.method) {
if ($.isEmptyObject(str) || null == str) {
return {
t: new Date().getTime()
};
} else {
return {
//
params: JSON.stringify(str),
t: new Date().getTime()
};
}
} else {
return JSON.stringify(str);
}
}
//
function processResponse(r) {
let str = {};
if (r.rows) {
str = r;
str.code = 0;
str.list = r.rows;
delete str.rows;
} else {
if (!r.error) {
if (0 <= r.code) {
str = r;
} else {
str.code = 0;
str.data = r;
}
} else {
str.code = -1;
str.message = r.message || r.error;
}
}
return str;
}