I have an Angular7 application and want to send a HTTP request to an API via an Angular CLI proxy. The API then responds with a JSON object. My configurations for the proxy are done in a proxy.conf.js.
A simple request with a simple target works fine. But I want to dynamically change the request before it's sent. I found an instruction at https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md#bypass-the-proxy but I just can't make it to work to dynamically change the target url.
My goal:
I want to send a request to a weather API. The url I send to that API must contain the latitude and longitude of a city. The city will be selected by a user. This user input should change the request target.
The request I am sending:
http://localhost:4200/forecast?lat=51.33962&lon=12.37129
This is my proxy.conf.js:
const PROXY_CONFIG = [
{
context: [
"/forecast",
],
target: "https://api.anyName.net/forecast/anyKey/37.8267,-122.4233",
changeOrigin: true,
secure: false,
pathRewrite: {
"^/forecast": ""
},
bypass: function(req, res, proxyOptions) {
if (req.query.lat) {
let LATITUDE = req.query.lat;
let LONGITUDE = req.query.lon;
const newTarget = "https://api.anyName.net/forecast/anyKey/"+LATITUDE+","+LONGITUDE;
req.target = newTarget;
return newTarget;
}
},
}
];
module.exports = PROXY_CONFIG;
I am not quite sure how to use the bypass function. What could I do to change the target?