关于angular4如何设置proxy代理实现跨域

1.首先我们创建代理配置文件proxy.conf.json

假如你的后端服务的访问地址为“http://localhost:3000”,以下为proxy.conf.json的例子:

{

  "/api": {  

    "target": "http://localhost:3000",

    "secure": false

  }

}

2.改写package.json

修改启动命令,默认使用npm start时使用代理文件配置的代理

"start":"ng serve --proxy-config proxy.conf.json",


其中"/api"是你需要代理的路径,比如你的后台接口链接是http://localhost:3000/api/getAllUser,那么在代码中你只需写成“/getAllUser”即可。

结果就是http://localhost:4200/api/getAllUser(cli默认端口为4200,根据自己的启动端口编写)能够代理访问到http://localhost:3000/api/getAllUser的内容。

注:如果没有生效的话,试试重启项目或者重新npm install一下项目,保证依赖完整。

你可能感兴趣的:(关于angular4如何设置proxy代理实现跨域)