我正在尝试将HTTP POST发送到我的服务器,我是这样做的:
var headers = new Headers({ 'Access-Control-Request-Headers': "Content-Type", 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
console.log(JSON.stringify(library) + " " + SERVER + "/library");
this.http.post(SERVER + "/library", JSON.stringify(library), options)
.subscribe(data => {console.log(data.json())});
但我收到Refused to set unsafe header "access-control-request-headers"
错误。如果我在没有'Access-Control-Request-Headers': "Content-Type"
的情况下发送POST,我会收到Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response
。有谁知道如何解决这个问题?提前谢谢。
答案 0 :(得分:2)
我通过在服务器端添加下一个代码解决了这个问题:
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}