我尝试从 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() {
}
}
我是一名优秀的程序员,十分优秀!