【问题标题】:Angular - Connects to Proxy server and gets response but then shows Error occured while trying to proxy to: localhost to actual serverAngular - 连接到代理服务器并获得响应,但随后显示尝试代理时发生错误:本地主机到实际服务器
【发布时间】:2017-10-15 19:44:30
【问题描述】:

我是 Angular(2,4) 的新手。我试图连接到代理服务器。

在项目根目录添加proxy.config.json

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

然后在 package.json 中的start 中添加代理配置

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

现在在组件中我有一个登录方法来连接到服务器。

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

在身份验证服务中,我有以下代码。

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

连接正常。服务器使用正确的 JSON 数据进行响应。但我将无法登录。

真正的问题

这很奇怪。有时它工作正常,但大多数情况下即使在正确连接到服务器后也会出现问题。服务器使用 JSON 数据进行响应。然后在终端控制台中显示

[HPM] 尝试将请求 /api/v1/login 从 localhost:4200 代理到 http://: (ECONNRESET) (https) 时出错 ://nodejs.org/api/errors.html#errors_common_system_errors)

如果我检查 chrome 网络控制台,请求的状态是 OK。 但在预览选项卡中,它显示来自服务器的 JSON,然后附加以下字符串“尝试代理时发生错误到:localhost:4200/api/v1/login"

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

因为那个 JSON 解析出错了。

为什么有时会出现问题而不总是发生?真正的问题是什么?

P.S.:我使用的是 angular - 4.0.0,angular-cli 1.0.2

【问题讨论】:

  • 所以错误是由于无效的 JSON 而发生的。
  • 由于 JSON 发生解析错误。但我猜是连接问题
  • 可能你的后端没有给出 json 响应。可能它还没有准备好服务请求 - 重新启动?
  • 尝试使用其他工具(邮递员、curl)发送请求并验证结果
  • 嘿@iCode,你解决了吗。我有同样的问题

标签: angular angular-cli econnreset


【解决方案1】:

当您使用 Angular CLI 时,您正在使用 Webpack 开发服务器:Link to their Github. 您所做的只是将代理文件的路径传递到 CLI,然后将其下载并传递到 webpack-dev-服务器。

this issue,据报道删除“/api/*”中的*可能会解决您的问题。

【讨论】:

    【解决方案2】:
    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"
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      我也遇到了这个问题,最后我添加了一个过滤响应的函数:

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

      这里有一些参考:

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

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

      希望你能找到更好的解决方案


      使用 HttpClient 代替 Http

      【讨论】:

      • 这不是解决问题的真正方法,它只是解决症状。此外,使用 HttpClient 也不是解决方案。 (无论如何我都遇到了这些问题)
      猜你喜欢
      • 2019-01-30
      • 1970-01-01
      • 2014-11-29
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 2023-03-17
      相关资源
      最近更新 更多