我正在尝试为我的 Web 应用程序创建用户管理 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.
角标头.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',
})
};
角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);
});
}
原文由 laprof 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可能需要在 Spring Boot 端配置 CORS。请在您的项目中添加以下课程。
更新:
要将令牌附加到每个请求,您可以创建一个拦截器,如下所示。
例子