Angular 或 Angular 6 中的跨域资源共享 (CORS).当您使用不同端口在本地主机上进行跨域调用时出现问题 [英] Cross Origin Resource Sharing (CORS) in Angular or Angular 6. Problem while you make cross domain calls on localhost with different ports

查看:32
本文介绍了Angular 或 Angular 6 中的跨域资源共享 (CORS).当您使用不同端口在本地主机上进行跨域调用时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过从 angular 6 应用程序调用 Spring Boot 应用程序的情况.当我以角度调用在不同端口上运行的应用程序的 HTTP post 方法时,它会引发异常.

I have come across a situation where I make a call from my angular 6 application to my spring boot application. When I call an HTTP post method in angular to the application running on a different port it throws an exception.

在 'http://localhost:8080/api' 处访问 XMLHttpRequest 来自 origin 'http://localhost:4200' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:确实如此没有 HTTP 正常状态.

Access to XMLHttpRequest at 'http://localhost:8080/api' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我的 Angular 应用程序在 'http://localhost:4200' 端口号:4200 上运行我的 Spring Boot 应用程序在http://localhost:8080/api"上运行:端口号:8080.

My Angular application Running on 'http://localhost:4200' port number:4200 My Spring Boot application running on 'http://localhost:8080/api': port number:8080.

没有直接的答案可以解决这个问题.很少有黑客可以禁用 chrome 中的安全性,使用 NGINX 可以解决这个问题.

There is no direct answer to solve this problem. There are few hacks to disable the security in chrome and using NGINX you can resolve this issue.

推荐答案

解决上述问题

  1. 首先需要共享4200端口的Spring引导资源.用@CrossOrigin(origins = "http://localhost:4200") 您要共享的资源.

  1. First you need to share the Spring boot resource for the port 4200. Annotate the class or method with @CrossOrigin(origins = "http://localhost:4200") of resource you want to share.

你必须在 Angular 应用程序中配置代理.所以在 angular root 应用程序中创建一个 proxy.json 文件.内容如下

Yo have to configure proxy in angular application. So create a proxy.json file in angular root application. and the content goes below

{
"/api/*": {
    "target": "http://localhost:8080",
    "secure": "false",
    "logLevel": "debug",
    "changeOrigin": true
}

}

然后运行 ​​ng serve --proxy-config proxy.json 这个命令它会编译代码.您应该会在控制台上看到类似的内容.

And then run ng serve --proxy-config proxy.json this command it will compile the code. You should see something like this on a console.

building modules 3/3 modules 0 active[HPM] Proxy created: /api -> 
http://localhost:8080 Subscribed to http-proxy events: [ 'error', 'close' ]

这篇关于Angular 或 Angular 6 中的跨域资源共享 (CORS).当您使用不同端口在本地主机上进行跨域调用时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆