Angular-CLI代理不起作用

时间:2017-04-25 16:56:07

标签: angular proxy angular-cli

我正在使用一个新的angular-cli“my-project”并创建了一个简单的虚拟服务。我希望此服务连接到本地计算机上的laravel后端。我找到了Angular-CLI proxy to backend doesn't work,但即使这些步骤也不适合我。 Chrome仍然会访问localhost:4200。

我的服务

import { Injectable } from '@angular/core';
import {Http, Response} from '@angular/http';

@Injectable()
export class DummyService {

  constructor(private http: Http) {
    console.log('Hello dummyService');
  }

  getMessages() {
    return this.http.get('/backend/public/api/auth/login').map((res: Response) => res.json());
  }

}

我的proxy.config.json

{
  "/backend": {
    "target": "http://localhost:81/laravelapi",
    "secure": false,
    "pathRewrite": {"^/backend" : ""},
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

和我的开始属于package.json

"start": "ng serve --proxy-config proxy.config.json",

启动时,我收到以下日志消息:

** NG Live Development Server is running on http://localhost:4200 **
  0% compiling
 10% building modules 1/1 modules 0 active
 10% building modules 4/4 modules 0 active[HPM] Proxy created: /backend  ->  http://localhost:81/laravelapi
[HPM] Proxy rewrite rule created: "^/backend" ~> ""
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]

 10% building modules 4/5 modules 1 active ...ct\node_modules\jquery\dist\jquery.js
 10% building modules 5/6 modules 1 active ...e_modules\metismenu\dist\metisMenu.js

最后:

webpack: Compiled successfully.
[HPM] Rewriting path from "/backend/public/api/auth/login" to "/public/api/auth/login"
[HPM] GET /backend/public/api/auth/login ~> http://localhost:81/laravelapi

但是在浏览器中我得到了     获取http://localhost:4200/backend/public/api/auth/login 404(未找到)

所以似乎没有用。 我正在使用“@ angular / cli”:“^ 1.0.0”。

任何想法我做错了什么?

我只想在我的代码中写 /后端/公/ API /认证/注册 那些电话应该去 http://localhost:81/laravelapi/public/api/auth/login 在我的本地机器上进行开发。

thx任何建议! 彼得

2 个答案:

答案 0 :(得分:8)

你的网址是/ backend / public / api / auth / login,所以你的代理应该是这个 即后端/ *

{
  "/backend/*": {
    "target": "http://localhost:81/laravelapi",
    "secure": false,
    "pathRewrite": {"^/backend" : ""},
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

答案 1 :(得分:-1)

<强>步骤

1)在Angular CLI应用程序根文件夹中,创建一个名为proxy.conf.json

的新文件

粘贴到以下JSON对象中。

{
  "/*/*": {
    "target": "http://localhost:81",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

2)打开package.json文件并更改:

 "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },

......来:

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

3)

A)打开命令提示符

B)转到Angular Cli应用程序的根文件夹

C)输入npm start并按Enter键