Angular-连接到代理服务器并获得响应,但随后显示在尝试代理到localhost到实际服务器时发生错误 [英] Angular - Connects to Proxy server and gets response but then shows Error occured while trying to proxy to: localhost to actual server

查看:1056
本文介绍了Angular-连接到代理服务器并获得响应,但随后显示在尝试代理到localhost到实际服务器时发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

Added proxy.config.json in project root directory

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

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

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

连接正常.服务器以正确的JSON数据响应.但是我将无法登录.

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

实际问题

这很奇怪.有时它可以正常工作,但是即使正确连接到服务器,大多数情况下仍显示问题.服务器以JSON数据响应.然后在终端控制台中显示

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]尝试将请求/api/v1/login从localhost:4200代理到http://:(ECONNRESET)(https时发生错误 ://nodejs.org/api/errors.html#errors_common_system_errors)

[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)

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

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

由于JSON解析出错.

Because of that JSON parsing gets error.

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

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

PS :我使用的是angular-4.0.0,angular-cli 1.0.2

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

推荐答案

使用Angular CLI时,使用的是Webpack Dev Server:

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.

此问题上,据报道,删除了* "/api/*"可能会解决您的问题.

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

这篇关于Angular-连接到代理服务器并获得响应,但随后显示在尝试代理到localhost到实际服务器时发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆