我的休息应用程序有下一个问题。 我的后端有一个自定义身份验证处理程序
public class AutorizacionFilter extends OncePerRequestFilter {
@Autowired
UsuariosService usuarioService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String dominio = ((HttpServletRequest) request).getRequestURI();
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
filterChain.doFilter(request, response);
} else if (dominio.startsWith("/api/login") || dominio.startsWith("/api/usuarios")) {
filterChain.doFilter(request, response);
} else {
String token = request.getHeader ("Authorization");
if (token == null || !usuarioService.validarSesion(token)) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "your message goes here");
return;
}
filterChain.doFilter(request, response);
}
}
在我的Angular 5网页中,我有一个用于捕获401状态代码的拦截器
@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (!req.headers.has("Content-Type")) {
req = req.clone({
headers: req.headers.set("Content-Type", "application/json")
});
}
req = req.clone({ headers: req.headers.set("Accept", "application/json") });
console.log(JSON.stringify(req.headers));
return next.handle(req).do(
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log("Autorizacion OK!");
console.log("Code: " + event.status);
}
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("An error occurred:", err.error.message);
} else {
console.log(
`Backend returned code ${err.status}, body was: ${err.message}`
);
}
}
);}}
当toker到期时,拦截器无法解析答案并给我这个错误
(未知网址)的Http失败响应:0未知错误
我对httpClient的问题有很多关于空响应的问题,但我不明白如何修复/找到解决办法。
任何人都可以帮助理解这个问题。
由于
答案 0 :(得分:0)
感谢@Asura的回答,我设置了响应标头并解决了问题。 这是代码。
if (token == null || !usuarioService.validarSesion(token)) {
((HttpServletResponse) response).setHeader("Access-Control-Allow-Origin", "*");
((HttpServletResponse) response).setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}