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

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

问题描述

我遇到了从我的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 ="http://localhost:4200" rel ="nofollow noreferrer"> 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.

您必须在角度应用程序中配置代理.因此,在有角度的根应用程序中创建一个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).在具有不同端口的localhost上进行跨域调用时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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