Angular2+ provides a reverse proxy that can directly implement cross-domain in front-end code. The specific method is as follows:
A proxy.conf.json configuration file is created in the root directory of the angular project. The code example is as follows:
{
"/api": { // 将http://localhost:4200/api通过代理实际访问: http://www.hy.com/apis/api
"target": "http://www.hy.com/apis/", //【必须】:需要跨域的服务器地址
"logLevel": "debug", //调试用,如果代理成功,在命令行工具中会显示跨域的地址
"changeOrigin": true, //如果不是代理本机就【必须】设变true,否则可以不设置
"pathRewrite": { // 修改代理接口的路径地址
"^/api": ""
}
},
"/": { // 访问http://localhost:4200/ 实际访问http://www.hy.com/apis/
"target":"http://www.hy.com/apis"
}
}
Configure the package.json file in the root directory of the angular project, or run cmd directly: ng serve -o --proxy-config proxy.cong.json , as shown below:
above sea level start