Search code examples
angularjsproxyhttp-proxy-middleware

Angular 2.0 service call not going through http-proxy-middleware


I have an Angular 2.0 application and recently I added http-proxy-middleware with the following bs-config.js:

var proxyMiddleware = require('http-proxy-middleware');

module.exports = {
    server: {
        port: 3000,
        middleware: {
            1: proxyMiddleware('/WorkLocation', {
                target: 'http://localhost/Perform/Company/WorkLocation',
                changeOrigin: false,
                logLevel: 'debug'
            }),
            2: require('connect-history-api-fallback')({index: '/index.html', verbose: true})
        }
    }
};

Then I have a service like this:

export class WorkLocationsService extends BaseRestfulService<WorkLocationItemModel[]> {    

    private workLocationsServiceUrl: string = '/WorkLocation/EditList/111014/73442';

    constructor(protected _http: Http) { super(_http) }

    public getWorkLocations(): Observable<WorkLocationItemModel[]> {        
        return this.callApiEndPoint(null, this.workLocationsServiceUrl, HttpVerb.Get);
    };

When I start my application through npm start it pricks up the bs-config.js proxy settings and I see the following output:

[1] [HPM] GET /WorkLocation/EditList/111014/73442 -> http://localhost/Perform/Company/WorkLocation
[1] 17.02.09 20:44:09 404 GET /WorkLocation/EditList/111014/73442

So looks like HPM proxy is doing the right translation but in the line right below I get a 404 error on the GET coming from my WorkLocationService call. Why could my service not be going through the proxy if it looks to be properly configured? Am I missing something?


Solution

  • Turns out that my target was wrong.

    I had:

    target: 'http://localhost/Perform/Company/Worklocation
    

    and it had to be:

    target: 'http://localhost/Perform/Company'
    

    Since Worklocation was already part of the context I was passing.

    This is the code that is working for me now:

    var proxyMiddleware = require('http-proxy-middleware');
    
    module.exports = {
        server: {
            port: 3000,
            middleware: {
                1: proxyMiddleware('/WorkLocation', {
                    target: 'http://localhost/Perform/Company',
                    changeOrigin: true,
                    logLevel: 'debug'
                }),
                2: require('connect-history-api-fallback')({index: '/index.html', verbose: true})
            }
        }
    };