Cors Policy No Access-Control-Allow-Origin' 标头

Posted

技术标签:

【中文标题】Cors Policy No Access-Control-Allow-Origin\' 标头【英文标题】:Cors Policy No Access-Control-Allow-Origin' headerCors Policy No Access-Control-Allow-Origin' 标头 【发布时间】:2021-08-12 17:58:28 【问题描述】:

我在 Udemy 上使用 course Angular 和 Spring Boot,但我一直遇到这个错误

"访问 XMLHttpRequest 在 'http://localhost:8080/hello-world/path-variable/Karnage' 来自原点 “http://localhost:4200”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源”

我已经检查了这里包含单词 cors 的每一个问题,它让我在一个多星期的持续研究中处于停滞状态。

春季班:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


@CrossOrigin(origins="http://localhost:4200")
@RestController


public class HelloWorldController 
    
    

    
    
    @GetMapping(path = "/hello-world")
    public String helloWorld() 
        return "Hello World";
    

    @GetMapping(path = "/hello-world-bean")
    public HelloWorldBean helloWorldBean() 
        //throw new RuntimeException("some error has occurd");
        return new HelloWorldBean ("Hello World");
    

    @GetMapping(path = "/hello-world/path-variable/name")
    public HelloWorldBean helloWorldPathVariable(@PathVariable String name) 
    
        return new HelloWorldBean(String.format("Hello World, %s", name));
    


Spring 基本身份验证:

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter
 
    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http
        .csrf().disable()   
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
            //.formLogin().and()
            .httpBasic();
    
    
    

Angular 欢迎数据服务:

import  HttpClient, HttpHeaders  from '@angular/common/http';
import  Injectable  from '@angular/core';

export class HelloWorldBean 
  constructor(public message: string)  


@Injectable(
  providedIn: 'root'
)
export class WelcomeDataService 

  constructor(
    private http: HttpClient
  )  

  executeHelloWorldBeanService() 
    return this.http.get<HelloWorldBean>('http://localhost:8080/hello-world-bean');
  

  executeHelloWorldServiceWithPathVariable(name: any) 
    let basicAuthHeaderString = this.createBasicAuthenticationHttpHeader();

    let headers = new HttpHeaders(
      Authorization: basicAuthHeaderString

    )


    return this.http.get<HelloWorldBean>(
      `http://localhost:8080/hello-world/path-variable/$name`,
       headers 
    );
  

  createBasicAuthenticationHttpHeader() 
    let username = 'karnage'
    let password = '123'
    let basicAuthHeaderString = 'Basic ' + window.btoa(username + ':' + password);
    return basicAuthHeaderString;
  


Angular 欢迎组件:

import  Component, OnInit  from '@angular/core';
import  ActivatedRoute  from '@angular/router';
import  WelcomeDataService  from '../service/data/welcome-data.service';

@Component(
  selector: 'app-welcome',
  templateUrl: './welcome.component.html',
  styleUrls: ['./welcome.component.css']
)
export class WelcomeComponent implements OnInit 

  welcomeMessageFromService: any
  name = ''
  constructor(
    private service: WelcomeDataService,
    private router: ActivatedRoute)  

  ngOnInit(): void 
    this.name = this.router.snapshot.params['name']

  

  getWelcomeMessage() 
    //console.log(this.service.executeHelloWorldBeanService());
    this.service.executeHelloWorldBeanService().subscribe(

      response => this.handleSuccessfulResponse(response),

      error => this.handleErrorResponse(error)
    );
  

  getWelcomeMessageWithPath() 
    //console.log(this.service.executeHelloWorldBeanService());
    this.service.executeHelloWorldServiceWithPathVariable(this.name).subscribe(

      response => this.handleSuccessfulResponse(response),

      error => this.handleErrorResponse(error)
    );
  


  handleSuccessfulResponse(response: any) 

    console.log(response)
    this.welcomeMessageFromService = response.message
  

  handleErrorResponse(error: any) 
    console.log(error)
    this.welcomeMessageFromService = error.error.message
  

非常感谢。

【问题讨论】:

【参考方案1】:

我在更新项目时遇到了这个问题,并使用插件解决了这个问题。 Allow CORS: Access-Control-Allow-Origin

【讨论】:

安装插件,然后刷新该页面。可能需要重复几次 chrome.google.com/webstore/detail/allow-cors-access-control/… 我试过了,它已经给了我另一个 cors 错误,即“https status ok” 请帮帮我,我仍然找不到解决这个问题的方法..

以上是关于Cors Policy No Access-Control-Allow-Origin' 标头的主要内容,如果未能解决你的问题,请参考以下文章

has been blocked by CORS policy

跨域详解 been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the

前端跨域问题的解决方案Access to XMLHttpRequest at ‘http..’ from origin ‘null‘ has been blocked by CORS policy

ReactJS:对 fetch 的访问已被 CORS 策略阻止

Cors Policy 问题 Blazor WASM、Web API 和 Identity Server 4 和 IIS

Request Method: OPTIONS Access to XMLHttpRequest blocked by CORS policy: