Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Connects to Proxy server and gets response but then shows Error occured while trying to proxy to: localhost to actual server

I'm new to Angular(2,4). I was trying to connect to proxy server.

Added proxy.config.json in project root directory

{
    "/api/*": {
        "target": "http://<server_ip_address>:<port>",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug"
    }
}

Then added the proxy config in start in package.json

"scripts": {
        "ng": "ng",
        "start": "ng serve --proxy-config proxy.config.json",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
    },

Now in component I have a login method to connect to server.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { AlertService, AuthenticationService } from '../services/index';

@Component({
    moduleId: module.id.toString(),
    templateUrl: 'login.component.html'
})

export class LoginComponent implements OnInit {
    model: any = {};
    loading = false;
    returnUrl: string;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private authenticationService: AuthenticationService,
        private alertService: AlertService) { }

    login() {
            this.loading = true;
            this.authenticationService.login(this.model.email, this.model.password)
                .subscribe(data => {
                    localStorage.setItem('currentUser', JSON.stringify(data));
                    this.router.navigate([this.returnUrl]);
                },
                error => {
                    this.alertService.error(error);
                    this.loading = false;
                },
                () => {
                    console.log("Subscribed Else");
                });
        }
}

In Authentication Service I have following code.

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';


@Injectable()
export class AuthenticationService {
    headers = new Headers();

    constructor(private http: Http) {
        this.headers.append("Content-Type", "application/json");
    }

    login(email: string, password: string) {
        return this.http.post('/api/v1/login', { email: email, password: password }, { headers: this.headers })
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(response: Response) {
        let user = response.json();
        return user;
    }
    private handleError(error: Response | any) {
        // In a real world app, you might use a remote logging infrastructure
        let errMsg: string;
        let resMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            resMsg = body['message'];
            console.log(body);
            console.log(resMsg);
        } else {
            resMsg = error.message ? error.message : error.toString();
        }
        return Observable.throw(resMsg);
    }
}

The connection works fine. The server responds with proper JSON data. But I would be able t login.

Real Problem

It''s weird. Sometimes it works fine, but mostly it shows issue even after connecting to server properly. The server responds with JSON data. Then in terminal console it shows

[HPM] Error occurred while trying to proxy request /api/v1/login from localhost:4200 to http://: (ECONNRESET) (https ://nodejs.org/api/errors.html#errors_common_system_errors)

If I check the chrome network console, the status of request is OK. But in the preview tab, it shows JSON from server and then it appends with following string "Error occured while trying to proxy to: localhost:4200/api/v1/login"

{"name":"something","id":"12sde"}Error occured while trying to proxy to: localhost:4200/api/v1/login

Because of that JSON parsing gets error.

Why issue happens sometimes and not always? And what's the actual issue?

P.S.: I'm using angular - 4.0.0, angular-cli 1.0.2

like image 541
iCode Avatar asked May 16 '17 16:05

iCode


1 Answers

When you are using the Angular CLI, you are using the Webpack Dev Server : Link to their Github. All you are doing is passing the path to your proxy file into the CLI, which then downloads it and passes it into webpack-dev-server.

On this issue, it's reported that removing the * in "/api/*" might fix your problem.

like image 98
Rob Avatar answered Nov 09 '22 16:11

Rob