简体   繁体   English

不允许多个 CORS 标头“Access-Control-Allow-Origin”/缺少 CORS 标头“Access-Control-Allow-Origin”)

[英]Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed / CORS header ‘Access-Control-Allow-Origin’ missing)

I'm having issues with the CORS headers when sending an HTTP request from my Angular 7 application (hosted on http://localhost:4200 ) to my Spring-Boot application (hosted on https://localhost:8924 ) from Firefox.当我从 Angular 7 应用程序(托管在http://localhost:4200 上)向我的 Spring-Boot 应用程序(托管在https://localhost:8924 上)从 Firefox 发送 HTTP 请求时,我遇到了 CORS 标头问题。

I have a CORS filter in my Spring-Boot application that is added to my request:我的 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);
    }

When sending the request, the Firefox console returns this error message:发送请求时,Firefox 控制台返回此错误消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8924/api/auth/signin .跨域请求被阻止:同源策略不允许读取位于http://localhost:8924/api/auth/signin的远程资源。 (Reason: Multiple CORS header 'Access-Control-Allow-Origin' not allowed). (原因:不允许多个 CORS 标头“Access-Control-Allow-Origin”)。

Commenting out the Access-Control-Allow-Origin:注释掉 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);
        }
    }
}

Returns this error message:返回此错误消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8924/api/auth/signin .跨域请求被阻止:同源策略不允许读取位于http://localhost:8924/api/auth/signin的远程资源。 (Reason: CORS header 'Access-Control-Allow-Origin' missing). (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

src/app/home/login.component.ts extract 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 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);
  }
}

How does the response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Origin", "*"); line set multiple headers when included but none when I remove it?行在包含时设置多个标题,但在删除时没有设置?

Did you try enabling @CrossOrigin() in you springboot controller.您是否尝试在 springboot 控制器中启用@CrossOrigin() Below is the basic snippet.下面是基本片段。

@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));
}

For more info visit Enabling CORS有关更多信息,请访问启用 CORS

I had the same problem.我有同样的问题。 It was solved by above solution.通过上面的解决方法解决了。 You must not be CORS problem when using Internet Explorer.您在使用 Internet Explorer 时一定不是 CORS 问题。

This has solved the issue for me:这为我解决了这个问题:

if(!response.containsHeader("Access-Control-Allow-Origin"))
{
    response.addHeader("Access-Control-Allow-Origin", "*"); 
}

Not the ideal way to get it to work不是让它工作的理想方式

In my case this happens when i set both CORS support in nginx conf file and Django middleware.在我的情况下,当我在 nginx conf 文件和 Django 中间件中设置 CORS 支持时会发生这种情况。

Nginx part: 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 part:姜戈部分:

MIDDLEWARE = (
    'corsheaders.middleware.CorsMiddleware',

Solution was very simple - i just remove CORS part in nginx and all works perfectly解决方案非常简单 - 我只是删除了 nginx 中的 CORS 部分并且一切正常

location / {
    uwsgi_pass  django_upstream;
    include     uwsgi_params;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 原因:缺少 CORS header 'Access-Control-Allow-Origin' - Reason: CORS header ‘Access-Control-Allow-Origin’ missing “cors header&#39;access-control-allow-origin&#39;missing”拒绝请求,即使允许来源 - “cors header ‘access-control-allow-origin’ missing” denies request, even though origin is allowed CORS:不存在“ Access-Control-Allow-Origin”标头Angular 2 - CORS : No 'Access-Control-Allow-Origin' header is present Angular 2 Angular 2打字稿-启用CORS标头&#39;Access-Control-Allow-Origin&#39; - Angular 2 Typescript - Enable CORS header ‘Access-Control-Allow-Origin’ 如果 CORS 标头“Access-Control-Allow-Origin”为“*”,则不支持凭据 - Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’ “CORS:不存在‘Access-Control-Allow-Origin’header”,但存在 - “CORS: No 'Access-Control-Allow-Origin' header is present ”, but it is present Cors 策略无访问控制允许来源' header - Cors Policy No Access-Control-Allow-Origin' header 用于 https 的 CORS Access-Control-Allow-Origin - CORS Access-Control-Allow-Origin for https CORS 访问控制允许来源 iOS - CORS Access-Control-Allow-Origin iOS 405方法不允许,并且“ tcpdump说它已发送出去,” CORS头“ Access-Control-Allow-Origin”丢失了” - 405 Method Not Allowed and “CORS header ‘Access-Control-Allow-Origin’ missing” although tcpdump says it's being sent out
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM