簡體   English   中英

添加了 cors 映射的 Angular/Spring - 被 CORS 策略阻止:請求的資源上不存在“Access-Control-Allow-Origin”標頭

[英]Angular/Spring with cors mapping added - blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

我有一個簡單的 Angular 應用程序,它以這種方式向端點執行發布請求:

login(username:string, password:string){

   return this.http.post<String>('localhost:9090/helios-admin/api/auth/login',{
    "username": username,
    "password":password
});
}

但是引發了 CORS 政策的錯誤。 在我的 Spring 應用程序中,即公開端點的應用程序,我以這種方式設置了 cors 映射:

@Configuration
@EnableWebMvc
public class MyWebMvcConfig implements WebMvcConfigurer{

    @Override
       public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("*")
                        .allowedMethods("GET","POST", "OPTIONS");
       }

}

我遇到了同樣的問題,但在另一個應用程序中, 提出了一個問題,得到了響應並正確使用了它。 現在有了這個 angular 項目,它就行不通了。 我必須改變什么嗎?

編輯這是我在 Spring Boot 中的控制器

@CrossOrigin
    @PostMapping(PathConstants.LOGIN_ACTION)
    @ApiOperation("Login into Helios administrational console.")
    @Override
    public ResponseEntity<?> autenticate(@Valid @RequestBody LoginRequest request) {
        Authentication auth = authManager
                .authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(auth);
        String token = jwtProvider.generateToken(auth);
        return ResponseEntity.ok(new JwtAuthResponse(token));
    }

更新

問題出在 url 中:它想要一個'http://localhost:9090/helios-admin/api/auth/login' ,所以使用 http. 愚蠢的錯誤。
現在我有了一個新的。
它說:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

所以我補充說:

.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
                        "Access-Control-Request-Headers")
                .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")

並在角度

 this.httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json',
        'Access-Control-Allow-Origin':'*'})
      };

   return this.http.post<String>('http://localhost:9090/helios-admin/api/auth/login',{
    "username": username,
    "password":password
}, this.httpOptions).pipe(catchError(this.errorHandler));

但不起作用。

在rest api控制器類方法之前添加@CrossOrigin注解。

例子

@CrossOrigin
@RequestMapping(value = "/login", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseBean> postUserLogin(@RequestBody LoginDTO loginDTO) {
    //TODO
}

你可以這樣試試

public httpOptions;

login(username:string, password:string){
 this.httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': <some data> })
    };

   return this.http.post<String>(
    'localhost:9090/helios-admin/api/auth/login',
    { "username": username, "password":password },
    this.httpOptions
 );
}

您應該將配置添加到 Spring 以允許 CORS

我是這樣制作的:

爪哇

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

科特林

@EnableWebMvc
class WebConfig : WebMvcConfigurer {
    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
    }
}

你可以在這里看到春天的另一種方式。 祝你好運

https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

https://www.baeldung.com/spring-cors

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM