I am using angularjs2 in frontend & Java Spring as backend rest api & getting the error.
XMLHttpRequest cannot load 'Some url'. Request header field appkey is not allowed by Access-Control-Allow-Headers in preflight response.
this is my angular code.
private logInUrl = 'Some url'; // URL to JSON file
authenticateUserCredentials(logIn: LogIn): Observable<ResponseClass> {
let body = JSON.stringify(logIn);
let headers = new Headers();
headers.append('Content-type', 'application/json');
headers.append('appKey', 'superadmin');
let options = new RequestOptions({ headers: headers });
return this.http.post(this.logInUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
and server side code in which we have used filter.
public final class CorsFilter extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
// response.addHeader("Access-Control-Allow-Headers", "Content-type,X-Requested-With,Origin,accept");
response.addHeader("x-access_token","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
response.addHeader("Access-Control-Max-Age", "1800");//30 min
filterChain.doFilter(request, response);
}
}
In PostMan app the rest api is working fine with both the headers appKey & Content-type
Is this the correct way to implement appKey header or please suggest any other way to send the custom header or custom data in predefine headers.
OPTIONSone, be sure to allowOPTIONSin your requests. - Supamiu