gpt4 book ai didi

java - 如何将 CORS header 设置为内部服务器错误响应?

转载 作者:搜寻专家 更新时间:2023-11-01 03:04:19 25 4
gpt4 key购买 nike

我有一个带有 REST 接口(interface)的 Java 应用服务器,由 resteasy 提供,我有下面的 CORS 过滤器

@Provider
public class CORSFilter implements ContainerResponseFilter {

public void filter(ContainerRequestContext cReq, ContainerResponseContext cResp) {
cResp.getHeaders().add("Access-Control-Allow-Origin", "*");
cResp.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, auth-token");
cResp.getHeaders().add("Access-Control-Allow-Credentials", "true");
cResp.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
cResp.getHeaders().add("Access-Control-Max-Age", "1209600");
}

}

所有请求都返回 CORS header :

OPTIONS 200 OK
Access-Control-Allow-Credentials:"true"
Access-Control-Allow-Headers:"origin, content-type, accept, authorization, auth-token"
Access-Control-Allow-Methods:"GET, POST, PUT, DELETE, OPTIONS, HEAD"
Access-Control-Allow-Origin:"*"
Access-Control-Max-Age:"1209600"
Allow:"HEAD, GET, OPTIONS"
Connection:"keep-alive"
Content-Length:"18"
Content-Type:"text/plain"
Date:"Thu, 15 Jan 2015 15:23:01 GMT"
Server:"WildFly/8"

除非我有一个返回错误代码 500 的内部异常:

GET 500 Internal Server Error
Connection:"keep-alive"
Content-Length:"8228"
Content-Type:"text/html; charset=UTF-8"
Date:"Thu, 15 Jan 2015 15:23:01 GMT"

如何让 500 个响应包含这些 header ?

最佳答案

使用 ExceptionMapper :

@Provider
public class CorsExceptionMapper implements ExceptionMapper<Exception> {

@Override
public Response toResponse(Exception ex) {
ResponseBuilder responseBuilder = Response.serverError();
responseBuilder.header("Access-Control-Allow-Origin", "*");
responseBuilder.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, auth-token");
responseBuilder.header("Access-Control-Allow-Credentials", "true");
responseBuilder.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
responseBuilder.header("Access-Control-Max-Age", "1209600");
return responseBuilder.build();
}

}

为避免标题重复,您应该使用:

cResp.getHeaders().putSingle() 

ContainerResponseFilter 中。

关于java - 如何将 CORS header 设置为内部服务器错误响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27968190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com