16

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

5
  • so the error happens because of invalid JSON.
    – Sibiraj
    Commented May 17, 2017 at 10:05
  • Parse error happens because of JSON. But issue with connection I guess
    – iCode
    Commented May 19, 2017 at 16:00
  • Probably your back-end gives not a json response. May be it is not ready to serve request - restarting? Commented Jun 8, 2017 at 16:32
  • try to send requests with some other tool (postman, curl) and verify result
    – solomkinmv
    Commented Jun 14, 2017 at 14:58
  • 2
    Hey @iCode, did you solve it. I have same issue Commented Dec 30, 2018 at 10:21

4 Answers 4

2

Downgrading my node version from the current version to the recommended version helped me with a similar issue.

1
  • 1
    Thanks. More me upgrading to node v18.17.0 worked Commented Jul 25, 2023 at 14:15
1

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.

0
try to add "Connection": "keep-alive" to your proxy.config.json like mentioned below

{
    "/api/*": {
        "target": "http://<server_ip_address>:<port>",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug",
        "headers": {
            "Connection": "keep-alive"
        }
    }
}
-2

I also had this problem, finally I add a function to filter the response:

private parseResponse(response) {
   return JSON.parse(response['_body'].replace(/}Error.*/, '}'))
}

Here are some refs:

https://github.com/angular/angular-cli/wiki/stories-proxy

https://github.com/angular/angular-cli/issues/889#issuecomment-290112673

Hope you could find a better solution


use HttpClient instead of Http

1
  • this is no real way of fixing the problem, it just addresses the symptoms. also, using HttpClient is no solution. (i'm having these problems regardless) Commented Dec 11, 2017 at 9:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.