我正在用Spring框架开发后端。我的前部是用角度框架写的。我的GET请求被CORS策略阻止了。
当我用以下角度函数请求GET资源时:
authenticate(credentials, callback) {
const headers = new HttpHeaders(credentials ? {
authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
} : {});
this.http.get("http://localhost:8080/user", {headers: headers}).subscribe(response => {
console.log(response);
console.log(this.authenticated);
if (response['name']) {
this.authenticated = true;
} else {
this.authenticated = false;
}
return callback && callback();
});
}我在“网络”选项卡中收到一个失败的请求。根据我的安全配置,有时我还会得到401,但在这两种情况下,我都会在控制台中得到“被cors阻塞”的消息。
我是正在发送请求的主计长:
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class AuthorizationController {
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping("/user")
public Principal user(Principal user) {
System.out.println(user);
return user;
}
}这里是我的Spring安全配置:
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.httpBasic()
.and().authorizeRequests().antMatchers("/**").permitAll()
.anyRequest().authenticated();
}注意:这不是我喜欢的配置。我用这个是因为这是我找到工作的唯一方法。有了这种配置,我的POST请求就可以工作了。但是,我前面描述的GET请求不适用于此配置。
任何提示或帮助都将不胜感激,如果您需要更多关于我的代码的信息,请告诉我。
发布于 2020-12-03 20:52:56
CORS在浏览器中工作。对Postman做同样的操作,它应该是成功的(如果Java代码是正确的)。
您是否设置并运行了一个角代理?似乎不是,因为您直接用域名调用API。
检查如何启用和使用代理https://angular.io/guide/build#proxying-to-a-backend-server
https://stackoverflow.com/questions/65133047
复制相似问题