【发布时间】:2019-10-22 01:34:33
【问题描述】:
我正在尝试为我的网络应用创建用户管理 API。当我从前端向后端发送 API 调用时,会发生 cors 错误。 cors问题如何解决?我读了很多帖子,但我没有任何进展。
createUser() API 调用后出错
Access to XMLHttpRequest at 'http://localhost:8080/user/create'
from origin 'http://localhost:4200' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
Redirect is not allowed for a preflight request.
Angular header.config.ts
export const HTTP_OPTIONS = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials' : 'true',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE, PUT, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With',
})
};
Angular rest-user.service.ts
public createUser() {
return this.httpClient.post(this.USER_ENDPOINT + 'create', HTTP_OPTIONS);
}
SpringConfig.class
@Configuration
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
SpringSecurityConfig.class
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and().oauth2Client()
.and().oauth2Login();
}
}
UserRestController.class
@PostMapping("/user/create")
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public void createUser(Principal principal) throws UserAlreadyExistsException {
userServiceFacadeImpl.createUser(principal.getName());
}
网络消息
更新 20.06.19
private createUser() {
const headersObject = new HttpHeaders();
this.oktaAuth.getAccessToken().then( (value) => {
headersObject.append('Authorization', 'Bearer ' + value);
headersObject.append('Content-Type', 'application/json');
const httpOptions = {
headers: headersObject
};
this.httpClient.post('http://localhost:8080/user/' + 'create', null, httpOptions);
});
}
【问题讨论】:
-
您需要将原点添加到您的 CORS 映射中。例如:
registry.addMapping("/**").allowedOrigins("http://localhost:4200");。见https://spring.io/guides/gs/rest-service-cors/ -
谢谢@youri,但这并不能解决问题。
标签: angular spring rest spring-boot http