Angular学习笔记28:Angular6中的跨域问题

在实际的开发过程中,会遇到要从两个不同的服务器上获取资源。

例如有两个接口:

a接口:/test1/hero/ 这个接口请求自http://127.11.11.11:9000的资源与数据

b接口:/test2/people/ 这个接口请求自http://134.22.22.22:5000的资源与数据

这里就存在跨域的问题,此时该如何是好呢?

在实际开发时候

Angular-cli 已经考虑到了这个问题

在项目的根目录下:新建一个Json文件,命名为:proxy.cong.json

{
  "/test1/": {
    "target": "http://127.11.11.11:9000",
    "secure": false
  },
  "/test2/": {
    "target": "http://134.22.22.22:5000",
    "secure": false
  },
}

此时当在本地开发的时候,

执行命令:

ng serve --proxy-config proxy.conf.json

也可以修改根目录下的 package.json  中的scripts为如下:

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

在请求以test1开头的接口时,就会代理到http://127.11.11.11:9000,

在请求以test2开头的接口的时候,就会代理到http://134.22.22.22:5000。

在构建部署发布的时候

修改nginx的default.conf:

location /test1/ {
    proxy_pass http://127.11.11.11:9000/test1/;
    proxy_redirect default;
}

location /test2/ {
    proxy_pass http://134.22.22.22:5000/test2/;
    proxy_redirect default;
}

猜你喜欢

转载自blog.csdn.net/wjyyhhxit/article/details/85028705