私は非常に奇妙な問題があります。 "ポストマン" を使用してAPIリクエストを作成しないとブラウザは何である ローカルのホストされたAPIは角4からアクセスできないhttp
:ローカルCLI(4200ローカルホスト)を使用して、アンギュラ4アプリケーションをホストさ
- 問題は、すべて正常に動作します。 今、
import { Headers, Http } from '@angular/http';
とobservablesを使ってAngularアプリにリクエストを統合しています。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:4040/registerの読み込みに失敗しました:プリフライトリクエストへの応答は、アクセス制御チェックに合格しない:いいえ「アクセス制御 - 許可 - 起源」ヘッダが上に存在します要求されたリソースOrigin '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; }
:
実行スリムアプリケーションをドッカーコンテナ内のローカルホストとは異なる起源を得るために - 同じ動作
許可-原点ヘッダを右に追加index.phpの上に
header('Access-Control-Allow-Origin: *');
- 同じ振る舞い
corsミドルウェアを使用すると、OPTIONSプリフライトリクエストを考慮していません – charlietfl