![](/img/trans.png)
[英]Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
[英]Cors Policy No Access-Control-Allow-Origin' header
我正在學習課程Angular 和 Spring 在 Udemy 上啟動,我一直遇到這個錯誤
“CORS 政策已阻止從源“http://localhost:4200”訪問“http://localhost:8080/hello-world/path-variable/Karnage”中的 XMLHttpRequest:對飛行前請求的響應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”header”
我已經檢查了這里所有包含 cors 字樣的問題,這讓我在一個多星期的持續研究中處於停滯狀態。
Spring Class:
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
}
}
非常感激。
我在更新項目時遇到了這個問題,並使用插件解決了這個問題。 Allow CORS: Access-Control-Allow-Origin
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.