2017-04-25 95 views
2

我正在使用新的angular-cli「my-project」並創建了一個簡單的虛擬服務。我希望將此服務連接到本地計算機上的laravel後端。我發現Angular-CLI proxy to backend doesn't work,但即使這些步驟不適合我。 Chrome仍然會去localhost:4200。Angular-CLI代理不起作用

我的服務

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 

但在瀏覽器中我得到 GET http://localhost:4200/backend/public/api/auth/login 404(未找到)

因此它似乎沒有工作。 我正在使用「@ angular/cli」:「^ 1.0.0」。

任何想法我做錯了什麼?

我只是想我的代碼 /後端/公/ API /認證/註冊 裏面寫,這些電話應該去 http://localhost:81/laravelapi/public/api/auth/login 我的本地機器上進行開發。

thx任何建議! 彼得

+0

我使用類似的代理配置文件,它適用於我。 –

回答

4

你的URL是/後端/公/ API/auth /中登錄,所以您的代理應該是這個 即後端/ *

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

打我吧:) –

+0

@AhmedMusallam你可以+1 :);) –

+0

你是對的工作!多謝! – Peter

0

步驟

1)在角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)轉到您的角度CLI應用程序的根文件夾

C)輸入npm start,然後按回車