对一个API端点的请求导致500响应;其他API端点有效

时间:2019-02-13 06:58:16

标签: java spring-boot cors

我想将原点作为http://192.168.1.35:4200,并在springboot中创建了这样的CORSFilter:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

public CORSFilter() {
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    response.setHeader("Access-Control-Allow-Origin", "http://192.168.1.35:4200");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PATCH, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, X-Auth-Token, Origin, Content-Type, Accept, Auth_Token");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, res);
    }
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}

我创建了这样的请求,以从angular调用spring rest api:

 getAllUsers(): void {
    this.accessToken = JSON.parse(window.sessionStorage.getItem('token')).access_token;
    this.httpClient.get<User[]>(`${BASE_URL}/fam-users/user?access_token=${this.accessToken}`, httpOptions).subscribe(data => {
        this.dataChange.next(data);
    },
        (err: ApiError) => {
            this.snackBar.openSnackBar(err.error.message, 'close', 'red-snackbar');
        });

}

我发送请求时说

  

CORS策略已阻止从来源“ http://192.168.1.35:8080/fam-users/user?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTAwNDMwODMsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiRkFfQU1FTkQiLCJGQV9ORVciXSwianRpIjoiOWViMzZjNzAtOGUwOS00YzViLWI0OWQtNDNmZTRhOTkzNDgzIiwiY2xpZW50X2lkIjoiY2xpZW50Iiwic2NvcGUiOlsicmVhZCIsIndyaXRlIiwidHJ1c3QiXX0.IETZOJE8tIqNc249HmTcJHuZpZFY1TP4PLcbqUOF3qc”访问“ http://192.168.1.35:4200”处的XMLHttpRequest:请求的资源上没有“ Access-Control-Allow-Origin”标头。

但是来自“ http://192.168.1.35:4200”的所有其他请求都运行正常。

有人可以指导我解决此问题吗?

1 个答案:

答案 0 :(得分:0)

spring boo中有一个@CrossOrigin注释,例如:

@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
    System.out.println("==== in greeting ====");
    return new Greeting(counter.incrementAndGet(), String.format(template, name));
}

有关更多信息,请使用look