Hardik Sachdeva
Hardik Sachdeva

Reputation: 195

Request header field is not allowed by Access-Control-Allow-Headers in preflight response

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.

Upvotes: 1

Views: 9037

Answers (1)

slaesh
slaesh

Reputation: 16917

Angular2 is lower-casing the headers!

So Content-Type will be content-type, check that your backend will allow it! :)

See also this question: Cross orgin error in google chrome for the api call

There I explain how to test your Angular2-post-method to verify that the angular-part is working fine.

Upvotes: 0

Related Questions