Im using the Angular Seed project and trying to set up a proxy for api requests for a backend service that is running on a different port.
My code so far:
/* Add proxy middleware */
this.PROXY_MIDDLEWARE = [
require('http-proxy-middleware')({
ws: false,
target: 'http://localhost:5555',
router: {
// when request.headers.host == 'dev.localhost:3000',
// override target 'http://www.example.org' to 'http://localhost:8000'
//'http://localhost:5555/basepath/api' : 'http://localhost:7000/api'
}
})
];
Basically what I need to do is route any api matching http://localhost:5555/basepath/api to http://localhost:7000/api though I cant seem to get this working using http-proxy-middleware. I had it originally working using proxy-middleware but have switched as i need to modify the request headers and it seems that can only be done with http-proxy-middleware.
Spent a bit of time trying to get this work and this is what I ended up adding to project.config.ts within the constructor.
/* Add proxy middleware */
this.PROXY_MIDDLEWARE = [
require('http-proxy-middleware')(
'/basepath/api', {
ws: false,
onProxyReq: this.onProxyReq,
target: 'http://localhost:7000',
pathRewrite: {
'^/basepath/api' : '/api'
}
})
];
And this is the function I included below the constructor to add header to any requests that are proxied
onProxyReq(proxyReq: any , req: any, res: any) {
// add custom headers to request
proxyReq.setHeader('header_name', 'value');
}
来源:https://stackoverflow.com/questions/43067858/angular2-angular-seed-http-proxy-middleware-proxy-api-requests