CORS semi working between Angular App and Spring backend

丶灬走出姿态 提交于 2019-12-08 09:48:49

问题


Following this Spring tutorial I've added the following bean to my configuration logic. Note that I am using Spring Boot.

If you are using Spring Boot, it is recommended to just declare a WebMvcConfigurer bean as following:

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

Here's the thing: I am able to register a user from the client side:

onSubmit() {
  this.http.post('http://localhost:8080/register', this.registerForm.value)
    .subscribe(
      data => this.onRegisterSuccess(),
      err => alert(err.error.message)
    );
}

but I cannot access the endpoint for my OAuth2 token:

onSubmit() {
  const headers = new HttpHeaders()
    .set('Content-Type', 'application/x-www-form-urlencoded')
    .set('Authorization', 'Basic dGVzdGp3dGNsaWVudGlkOlhZN2ttem9OemwxMDA=');

  this.http.post('http://localhost:8080/oauth/token', this.loginForm.value, {headers: headers})
    .subscribe(
      data => this.onLoginSuccess(),
      err => alert(err.error.message)
    );
}

The resulting conversation:

I have no idea what the problem is.


回答1:


The authorization header is special. You need to add with a different method

.allowCredentials(false)



来源:https://stackoverflow.com/questions/47084086/cors-semi-working-between-angular-app-and-spring-backend

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