angular rxjs catchError status 是0 但实际请求状态码是401
api.service.ts
request(method, url, data = {}) {
const headers = {
'Content-Type': 'application/json',
'X-Token-With': this.token(),
'Authorization': localStorage.getItem('__accessToken') ? localStorage.getItem('__accessToken') : 'noAuth',
};
const trim = s => s === undefined || s === null ? '' : s;
const args: any = [[
window['baseUrl'],
url.replace(/:([^&;/?]+)/g, (...s) => trim(data[s[1]])),
].join('/')];
const params = Object.keys(data).reduce((obj, key) => {
obj[key] = trim(data[key]);
return obj;
}, {});
if (method === 'get' || method === 'delete') {
// args.push({ headers, params });
args.push({ headers, params, observe: "response", responseType: "json" });
} else {
args.push(params, { headers, observe: "response", responseType: "json" });
}
return this.http[method](...args).pipe(
map(response => {
if (response['ok']) {
return response['body'];
} else {
}
}),
catchError(error => this.handleError(error))
)
}
handleError(response: any) {
let errorMessage: any = {};
console.log(response)
if (response.error.status == 0) {
errorMessage = {
success: false,
status: 0,
data: 'Sorry, there was a connection error occurred. Please try again.'
};
return throwError(errorMessage);
}
if (response.error.status == 401) {
localStorage.clear();
this.router.navigate(['/login']);
}
if (response.error.status != 0 && response.error.status != 401) {
errorMessage = response.error;
const { status, statusText, error } = errorMessage;
const errors = error ? error.message : '服务器错误';
this.notify.create(
'error',
`${errors}`,
errorMessage.error,
);
return throwError(errorMessage);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果错误被浏览器安全机制拦截,那么状态会是0,而且其他所有信息都取不到。比如同源策略跨域访问拦截
求大神指路 感谢