axios
一些关于axios的使用技巧
拦截器
var baseUrl = "http://localhost:19800/api/";
const request = axios.create({
// api 的 base_url
baseURL: baseUrl,
timeout: 1000 * 60 * 5 //5分钟
// 请求超时时间
});
// response 拦截器
request.interceptors.response.use(
response => {
const res = response.data
if (res.statusCode !== 200) {
switch (res.statusCode) {
case 500:
app.errorNotify(res.message)
break;
//return Promise.reject(res) //服务器内部错误则不执行后续方法,不行,如果有按钮要处理什么的
default:
app.errorNotify(res.message)
break;
}
}
return res
},
error => {
app.errorNotify('请求接口失败,请确保连接到服务器')
return Promise.reject(error)
}
)
- 后端定义了ApiResult结构体,但是无法跑到拦截器的res里面。 //例如全局异常
- 原因:后端返回异常的时候,状态码是错误的,导致网络请求返回的也是错误
- 解决
context.Response.StatusCode = (int)HttpStatusCode.OK;
,原本是HttpStatusCode.InternalServerError
- 全局异常
//全局异常
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.OK;//!!!
context.Response.ContentType = "application/json";
var exception = context.Features.Get<IExceptionHandlerFeature>();
if (exception != null)
{
var log= NLog.LogManager.GetCurrentClassLogger();
log.Error(exception.Error);
var error = new ApiResult
{
StatusCode = 500,
Message = exception.Error.Message,
};
//https://www.cnblogs.com/jiyuwu/p/11882144.html
var serializerSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
DateFormatString = "yyyy/MM/dd HH:mm:ss",
// 设置为驼峰命名
ContractResolver = new LowercaseContractResolver()
};
var errObj = JsonConvert.SerializeObject(error, serializerSettings);
//var errObj = JsonConvert.SerializeObject(new JsonResult(error));
await context.Response.WriteAsync(errObj).ConfigureAwait(false);
}
});
}
);