【发布时间】:2021-08-23 13:57:04
【问题描述】:
我对 Angular 的世界还很陌生,如果这是一个愚蠢的问题,请原谅
我在尝试通过 Angular 应用程序访问 REST API 时遇到错误
从 'http://localhost:8080/bean/user' 访问 XMLHttpRequest 来源 'http://localhost:4200' 已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
这是我的 spring 安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
我尝试向 API 添加跨域注解,但也没有用
@CrossOrigin(origins="http://localhost:4200")
@GetMapping(path="/bean/{name}")
public Bean path(@PathVariable String name) {
return new Bean(name);
}
有人建议将内容类型设置为 text/plain,所以我也尝试了,但没有成功。这是一个可以调用的角度 sn-p
executeBeanService(name: string) {
let basicAuthHeaderString = this.createBasicAuthenticationHttpHeader();
let header = new HttpHeaders ( {
'Content-Type':'text/plain',
Authorization: basicAuthHeaderString
})
return this.http.get<Bean>(`http://localhost:8080/bean/${name}`,
{headers: header});
}
任何帮助将不胜感激!
【问题讨论】:
-
从您问题的标题看来,您似乎对邮递员的工作感到惊讶。浏览器执行跨域检查,而 Postman 不执行。这就是为什么。
-
您的 Spring 应用程序必须将标头发送回您的 Web 应用程序,告诉它允许跨源请求。例如,它来自的域。
标签: java angular spring-boot spring-security