Angular 5: Response for preflight has invalid HTTP status code 403

亡梦爱人 提交于 2019-12-04 13:11:21

PROBLEM :

For any Cross-Origin POST request, the browser will first try to do a OPTIONS call and if and only if that call is successful, it will do the real POST call. But in your case, the OPTIONS call fails because there is no 'Access-Control-Allow-Origin' response header. And hence the actual call will not be done.

SLOUTION :

So for this to work you need to add CORS Configuration on the server side to set the appropriate headers needed for the Cross-Origin request like :

  • response.setHeader("Access-Control-Allow-Credentials", "true");
  • response.setHeader("Access-Control-Allow-Headers", "content-type, if-none-match");
  • response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
  • response.setHeader("Access-Control-Allow-Origin", "*");
  • response.setHeader("Access-Control-Max-Age", "3600");

You need to ensure that the Spring accept CORS requests

Also if you have applied Spring security & require authorization headers for example for your API, then (only if you need to make your app support CORS) you should exclude the OPTIONS calls from authorization in your spring security configuration file.

It will be something like this:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {

  @Override
  public void configure(WebSecurity web) throws Exception {
    // Allow OPTIONS calls to be accessed without authentication
    web.ignoring()
        .antMatchers(HttpMethod.OPTIONS,"/**")

Note:

In production, probably it is better to use reverse proxy (like nginx) & not allow the browsers to call your API directly, in that case, you don't need to allow the OPTIONS calls as shown above.

Klimiuk S

I've had the exact same problem with Angular lately. It happens because some requests are triggering preflight requests eg. PATCH, DELETE, OPTIONS etc. This is a security feature in web browsers. It works from Swagger and Postman simply because they don't implement such a feature. To enable CORS requests in Spring you have to create a bean that returns WebMvcConfigurer object. Don't forget of @Configuration in case you made an extra class for this.

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
                        .allowedHeaders("*");
            }
        };
    }

Of course, you can tune this up to your needs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!