请求的资源(入口)上不存在'Access-Control-Allow-Origin'标头



我有一个spring引导项目用于后端,一个angular项目用于前端。我无法通过入口获得从后端到前端的响应。后端服务在端口8000上运行,前端服务在端口80上运行

端点-后端(http://localhost:8000/hello)和前端(http://localhost:80)都可以单独访问。我想让angular通过ingress与后端服务交互,这是不工作的

入口

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: api-call-app
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/enable-cors: "true"
nginx.ingress.kubernetes.io/configuration-snippet: |
more_set_headers "Access-Control-Allow-Origin: $http_origin";
nginx.ingress.kubernetes.io/cors-allow-origin: "*"
nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS, DELETE"
nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
nginx.ingress.kubernetes.io/cors-allow-headers: "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,X-CSRFToken"
spec:
rules:
- host: localhost
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: angular-service
port:
number: 80
- path: /hello
pathType: Prefix
backend:
service:
name: springboot-service
port:
number: 8000

春季启动代码

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class HelloController {

@GetMapping(value= "/hello", produces="text/plain")
public String hello()
{
return "hello";
}
...
<<p>角代码/strong>
export class HelloComponent implements OnInit {
resp: any
constructor(private http :HttpClient) { }
ngOnInit(): void {
let response= this.http.get("/hello", {responseType: 'text'});
response.subscribe((data)=>this.resp=(data));  
}

}

我看到的错误是-

从源'http://localhost'访问'http://localhost:8000/hello'的XMLHttpRequest已被CORS策略阻止:请求的资源上没有'Access- control - allow - origin '标头。

您需要在src文件夹下创建一个代理配置文件。即/proxy.conf.json

{
"/api/*": {
"target": "http://localhost:8090",
"secure": false,
"logLevel": "debug"
}
}

备注:" target ": " http://localhost:8090"是服务器端应用程序,对于不同的服务器会有所不同。当我们在非安全模式的HTTP模式下运行服务器时,将secure设置为false。

下一步,将proxyConfig键添加到angular。

"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "move-safe:build",
"proxyConfig": "src/proxy.conf.json"
}

https://levelup.gitconnected.com/fixing-cors-errors-with-angular-cli-proxy-e5e0ef143f85

相关内容