我有一個很奇怪的問題。本地託管API無法從Angular 4訪問http
- 本地使用XAMPP託管PHP超薄應用(本地主機:4040)
- 本地託管角4應用程序中使用CLI(本地主機:4200)
製作使用 「郵差」 瀏覽器API的請求,並沒有問題,一切工作正常。 現在我正在使用import { Headers, Http } from '@angular/http';
和observables將這些請求整合到我的Angular應用程序中。
未能加載http://localhost:4040/register:響應預檢請求未通過訪問控制檢查:
const requestUrl = 'http://localhost:4040/register'; const headers = new Headers({ 'content-type': 'application/x-www-form-urlencoded' }); this.http .get(requestUrl, {headers: headers}) .map(response => response.json()) .subscribe(result => { console.log(result); }, error => { console.log(error); });
請求始終以失敗否「訪問控制允許來源」標題存在於請求的資源。因此不允許訪問原產地'http://localhost:4200'。
但是:我肯定會發送這些頭文件!
public static function createJsonResponseWithHeaders($response, $requestedData)
{
// Add origin header
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$response = $response->withHeader('Access-Control-Allow-Methods', 'GET');
// Add json response and gzip compression header to response and compress content
$response = $response->withHeader('Content-type', 'application/json; charset=utf-8');
$response = $response->withHeader('Content-Encoding', 'gzip');
$requestedData = json_encode($requestedData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
$response->getBody()->write(gzencode($requestedData), 9);
if (!$requestedData || (count($requestedData) === 0)) {
return $response->withStatus(404)->write('Requested data not found or empty! ErrorCode: 011017');
}
return $response;
}
我已經嘗試過解決:
運行修身應用泊塢窗容器內,以獲得不同的產地除localhost - 同樣的行爲
添加允許原產地 - 頭向右index.php
header('Access-Control-Allow-Origin: *');
- 相同的行爲
使用cors中間件,您不會考慮OPTIONS預檢請求 – charlietfl