一般来说:
javascript
axios.request({
...// 请求config
}).then(
res => console.log('success',res),
err => console.log('err',err)
)
稍微拓展一下:
javascript
import axios,{ AxiosRequestConfig, AxiosError, AxiosResponse } from "axios";
import { getToken} from './token'
const http = axios.create({
timeout: 5000,
timeoutErrorMessage: '请求超时',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})
// 请求拦截
http.interceptors.request.use((config: AxiosRequestConfig)=>{
config.headers.Authorization = getToken()
return config;
},(err)=>{
})
// 响应拦截
http.interceptors.response.use((config)=>{
if(204 == config.status){
return Promise.reject(config);
}
return config;
},(err)=>{
if(err.code=="ECONNABORTED" || err.message=='Network Error' || err.message?.includes('timeout')){
app.$message({type:"error",message:err.message?err.message:"请求超时",center:true});
}
const status = err.response?err.response.status : null;
const message = err.response?err.response.data.message : 'Unknown error';
console.log("错误信息:",status,message);
if(err.response){
let statusCode = err.response.status;
let err_message = err.response.data.message;
switch(statusCode){
case 401://认证
app.$message({type:"error",message:err_message,center:true});
removeToken();
removeRefToken();
app.$router.replace("/login");
break;
case 403://授权
app.$message({type:"error",message:err_message,center:true});
app.$router.go(-1);
break;
case 500://网络错误
app.$message({type:"error",message:err_message,center:true});
break;
default://其他错误
app.$message({type:"error",message:err_message,center:true});
return;
}
}
})
})
export default http;
这里的axios大家配置的都大差不差,但是获取不到err,response的错误数据,浏览器无法解析。但是在线上的情况下,没有同源策略的阻碍,能拿到这个错误的响应 ,这里就会出现错误,这个错误一般出现在nginx没有配置的全面的情况下,导致的,导致非200的30系列,40系列,50系列的错误状态码和错误消息体无法正确的被浏览器拦截捕获。
解决办法,完善nginx配置
javascript
location /api/XXXXXX/ {
proxy_pass http://XXXXXX;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_body_buffer_size 128k;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
#CROS DEBUG
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Headers' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET,PUT,POST,DELETE,OPTIONS';
add_header 'Access-Control-Max-Age' '43200';
if ( $request_method = 'OPTIONS' ) {
return 204;
}
}