在angular.json中声明多个代理配置,并在proxy.conf.js中使用配置的键来指定需要使用哪个代理。
首先,在angular.json文件中添加多个代理配置。例如,我们可以声明两个代理配置,一个用于API1,另一个用于API2:
"projects": {
"my-app": {
"architect": {
"serve": {
"options": {
"proxyConfig": "src/proxy.conf.js",
"port": 4200
}
}
}
}
},
"api1": {
"target": "http://localhost:3000",
"secure": false
},
"api2": {
"target": "http://localhost:4000",
"secure": false
}
然后,在proxy.conf.js文件中使用代理配置的键来指定需要使用哪个代理。例如,我们可以为API1设置代理,如下所示:
const PROXY_CONFIG = {
"/api1": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true,
"pathRewrite": {
"^/api1": ""
}
}
};
module.exports = PROXY_CONFIG;
同样地,我们可以为API2设置代理,如下所示:
const PROXY_CONFIG = {
"/api2": {
"target": "http://localhost:4000",
"secure": false,
"changeOrigin": true,
"pathRewrite": {
"^/api2": ""
}
}
};
module.exports = PROXY_CONFIG;
最后,在我们的Angular应用程序中,我们可以在需要访问API1的地方使用“/api1”前缀,例如:
this.httpClient.get('/api1/items').subscribe(items => {
console.log(items);
});
同样地,为了访问API2,我们可以使用“/api2”前缀:
this.httpClient.get('/api2/users').subscribe(users => {
console.log(users);
});