【问题标题】: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
  }
}

非常感谢。

【问题讨论】:

    标签: javascript angular spring cors


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 2019-03-18
    • 2018-09-19
    • 2019-06-19
    • 2019-02-07
    • 2018-03-28
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 2021-07-15
    相关资源
    最近更新 更多