2016-02-13 45 views
1

角2訪問與此代碼我的PHP文件:角2訪問PHP API,而不是返回JSON,但返回文件

this._http.get('../api/src/1.0/get/images.php').subscribe(res => { 
    alert(JSON.stringify(res)); 
}); 

哪個給出了這樣的警告本地主機:3000說

{ 
    "_body": "<?php\n\nrequire_once '../../orm/connection.php';\n\n$images = R::getAll('SELECT * FROM image');\nheader('Content-Type: application/json');\necho json_encode($images);\n\n?>\n", 
    "status": 200, 
    "statusText": "Ok", 
    "headers": { 
     "Date": ["Sat", 
     " 13 Feb 2016 21:11:26 GMT"], 
     "Cache-Control": ["public", 
     " max-age=0"], 
     "Last-Modified": ["Sat", 
     " 13 Feb 2016 20:39:49 GMT"], 
     "Accept-Ranges": ["bytes"], 
     "ETag": ["W/\"a7-152dc5c6608\""], 
     "Content-Length": ["167"], 
     "Content-Type": ["application/octet-stream"] 
    }, 
    "type": 2, 
    "url": "http://localhost:3000/api/src/1.0/get/images.php" 
} 

PHP文件

<?php 

require_once '../../orm/connection.php'; 

$images = R::getAll('SELECT * FROM image'); 
header('Content-Type: application/json'); 
echo json_encode($images); 

?> 

我期待警報只包含JSON數據。 如果我通過它的網址去直接將文件只給我的JSON數據。 我將如何實現這一目標?

回答

1

要調用的位置../api/src/1.0/get/images.php靜態文件,你會得到它的內容。

您必須運行與服務器的PHP文件,比http.get(...)調用它可以用PHP本地主機服務器php -S localhost:3333,你需要在你的項目的根目錄運行此命令(PHP項目)

+0

所以你要說的是PHP運行本地主機的默認端口和2角運行本地主機端口3000,我需要在端口3000上運行PHP?我在哪裏可以使用php -S localhost:3333以及爲什麼使用3333? – ClickThisNick

+0

不好意思啊,那是隻例如:3333,你可以使用任何...最好是同時運行客戶端應用程序(角2)和API(PHP)與同一個服務器,只是在不同的文件夾... –

+0

有道理。一旦我去我的默認端口上的網站工作正常! – ClickThisNick

1

從你的反應得到,它看起來像您請求images.php"Content-Type":["application/octet-stream"]。嘗試配置http.get()索要JSON:

const HEADER = { headers: new Headers({ 'Content-Type': 'application/json' }) }; 
this._http.get('../api/src/1.0/get/images.php', HEADER).subscribe(res => { 
    alert(JSON.stringify(res)); 
}); 
+0

嗯仍與此頭相同 – ClickThisNick