Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refused to set unsafe header "access-control-request-headers" angular 2

Tags:

http

post

angular

I'm trying to send HTTP POST to the my server, I do it in this way:

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())});

but I'm getting Refused to set unsafe header "access-control-request-headers" error. If I'm sending POST without 'Access-Control-Request-Headers': "Content-Type" I'm getting Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. Does anyone know how to solve this problem? Thank in advance.

like image 290
Sergey Panov Avatar asked Oct 19 '22 00:10

Sergey Panov


1 Answers

I've solved this problem by adding next code on the server side:

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() {
    }

}

Thanks, Günter Zöchbauer

like image 68
Sergey Panov Avatar answered Oct 21 '22 05:10

Sergey Panov