Angular2/Angular seed http-proxy-middleware proxy api requests

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

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.

回答1:

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'); } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!