[英]Angular/Spring with cors mapping added - blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I have a simple Angular app that perform a post request to an endpoint this way:我有一个简单的 Angular 应用程序,它以这种方式向端点执行发布请求:
login(username:string, password:string){
return this.http.post<String>('localhost:9090/helios-admin/api/auth/login',{
"username": username,
"password":password
});
}
but the error of CORS policy is thrown.但是引发了 CORS 政策的错误。 In my Spring application, that is the one the expose the endpoint, I've set the cors mappings this way:在我的 Spring 应用程序中,即公开端点的应用程序,我以这种方式设置了 cors 映射:
@Configuration
@EnableWebMvc
public class MyWebMvcConfig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.allowedMethods("GET","POST", "OPTIONS");
}
}
I've encountered the same problem but with another application, asked a question , got the response and used it correctly.我遇到了同样的问题,但在另一个应用程序中, 提出了一个问题,得到了响应并正确使用了它。 Now with this angular project it doesn't work.现在有了这个 angular 项目,它就行不通了。 Do I have to change something?我必须改变什么吗?
EDIT This is my controller in Spring Boot编辑这是我在 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));
}
UPDATE更新
The problem was in the url: it wanted a 'http://localhost:9090/helios-admin/api/auth/login'
, so with http.问题出在 url 中:它想要一个'http://localhost:9090/helios-admin/api/auth/login'
,所以使用 http. Stupid error.愚蠢的错误。
Now I have a new one.现在我有了一个新的。
It says:它说:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
So I've added:所以我补充说:
.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")
and in angular并在角度
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));
but doesn't work.但不起作用。
Add @CrossOrigin annotation before the rest api controller class method.在rest api控制器类方法之前添加@CrossOrigin注解。
Example例子
@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
}
You can try like this你可以这样试试
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
);
}
You should add config to Spring to allow CORS您应该将配置添加到 Spring 以允许 CORS
I made like this:我是这样制作的:
java爪哇
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
Kotlin科特林
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun addCorsMappings(registry: CorsRegistry) {
registry.addMapping("/**")
}
}
Another ways for spring u can see here.你可以在这里看到春天的另一种方式。 Good luck祝你好运
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
https://www.baeldung.com/spring-cors https://www.baeldung.com/spring-cors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.