Angular:使用前端proxy代理解决跨域问题

①在项目文件的根目录下新建文件proxy.config.json

{
  "/": {
    "target": "http://127.0.0.1:3000",
    "secure": false
  }
}

//或者
{
  "/api": {  //适用场景:需要每个请求地址前加个’/api‘
    "target": "http://127.0.0.1:3000",
    "secure": false,
    "pathRewrite": {
      "^/api": ""  //代理后的请求地址http://127.0.0.1:3000/api/...  需要将’/api‘置换为空
    }
  }
}

②修改angular.json配置文件

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "angular-http:build",
            "proxyConfig": "proxy.config.json"  //新增
          },

③修改package.json配置文件

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

④重启项目ng serve --open

猜你喜欢

转载自www.cnblogs.com/xinhej/p/13394518.html