当我从Angular 7应用程序(托管在http://localhost:4200上向我的Spring-Boot应用程序(托管在https://localhost:8924上)发送HTTP请求时,CORS标头出现问题。
我的Spring-Boot应用程序中有一个CORS过滤器,该过滤器已添加到我的请求中:
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type");
response.addIntHeader("Access-Control-Max-Age", 3600);
if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
{
response.setStatus(HttpServletResponse.SC_OK);
}
else
{
filterChain.doFilter(request, response);
}
}
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.addFilterBefore(corsFilter(), SessionManagementFilter.class);
http.csrf().disable().
authorizeRequests()
.antMatchers("/api/auth/**","/api/MentorCalendar","/api/user/role/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
在发送请求时,Firefox控制台返回以下错误消息:
跨域请求被阻止:“同源起源”策略禁止读取http://localhost:8924/api/auth/signin处的远程资源。 (原因:不允许使用多个CORS标头“ Access-Control-Allow-Origin”。)
注释访问控制允许来源
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
// response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type");
response.addIntHeader("Access-Control-Max-Age", 3600);
if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
{
response.setStatus(HttpServletResponse.SC_OK);
}
else
{
filterChain.doFilter(request, response);
}
}
}
返回此错误消息:
跨域请求被阻止:“同源起源”策略禁止读取http://localhost:8924/api/auth/signin处的远程资源。 (原因:CORS标头“ Access-Control-Allow-Origin”缺失)。
src / app / home / login.component.ts提取
export class LoginComponent {
constructor(private LoginService: LoginService, private router: Router) {}
login(inputUsername, inputPassword){
this.LoginService.login({username: inputUsername, password: inputPassword})
.subscribe(data => {
localStorage.setItem("jwtToken", data.accessToken);
src / app / home / login.service.ts
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable()
export class LoginService {
loginUrl = "http://localhost:8924/api/auth/signin";
constructor( private http: HttpClient ) {}
login(loginCreds: any): Observable<any> {
return this.http.post<any>(this.loginUrl, loginCreds, httpOptions);
}
}
response.addHeader(“ Access-Control-Allow-Origin”,“ *”);如何?行设置多个标题(如果包含),而我将其删除则没有?
答案 0 :(得分:1)
您是否尝试在springboot控制器中启用 @CrossOrigin()。以下是基本代码段。
@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
有关更多信息,请访问Enabling CORS
我有同样的问题。通过以上解决方案解决了。使用Internet Explorer时,您一定不会出现CORS问题。
答案 1 :(得分:0)
这为我解决了这个问题:
if(!response.containsHeader("Access-Control-Allow-Origin"))
{
response.addHeader("Access-Control-Allow-Origin", "*");
}
不是使其正常工作的理想方法
答案 2 :(得分:0)
在我的情况下,当我在nginx conf文件和Django中间件中同时设置了对CORS的支持时,就会发生这种情况。
Nginx部分:
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
Django部分:
MIDDLEWARE = (
'corsheaders.middleware.CorsMiddleware',
解决方案非常简单-我只删除了nginx中的CORS部分,并且一切正常
location / {
uwsgi_pass django_upstream;
include uwsgi_params;
}