gpt4 book ai didi

java - CORS 策略不起作用,因为所有响应 header 均已设置,但仍然出现此错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:14:24 25 4
gpt4 key购买 nike

我尝试从 Servlet java 类中的 POST 方法获取响应。我尝试设置所有标题,但总是出现错误:

Access to XMLHttpRequest at 'XXX' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是我的标题:

@WebServlet(asyncSupported = true,urlPatterns = {"/Mitarbeiter_Einzel_Update"})
public class Mitarbeiter_Einzel_Update extends HttpServlet {
private static final long serialVersionUID = 1L;

public Mitarbeiter_Einzel_Update() {
super();
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
response.addHeader("Access-Control-Max-Age", "1728000");
response.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");

[...]

}

}

最佳答案

您应该创建 servlet Filter 来检查请求方法是否为“OPTIONS”

    import javax.servlet.Filter;

public class CorsFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {

HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;

resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
//resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
resp.setHeader("Access-Control-Allow-Credentials", "true");

if("OPTIONS".equals(req.getMethod())) {
resp.setHeader("Access-Control-Allow-Methods", req.getHeader("Access-Control-Request-Method"));
resp.setHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
resp.setHeader("Access-Control-Max-Age", "3600");

resp.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(request, response);
}
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void destroy() {
}
}

关于java - CORS 策略不起作用,因为所有响应 header 均已设置,但仍然出现此错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59250040/

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