Angular - Connects to Proxy server and gets respon

2020-06-11 09:18发布

问题:

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

回答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.



回答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