2017-10-06 36 views
-1

我有一個很奇怪的問題。本地託管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: *'); - 相同的行爲

回答

0

對不起,我的壞。解決方案很簡單:

請求中的「緩存控制」標題似乎不被允許,儘管在用郵差測試api時它工作正常。 我從請求中刪除標題,一切運行良好。

+0

使用cors中間件,您不會考慮OPTIONS預檢請求 – charlietfl

0

由於CORS未正確設置,您的請求被阻止。還有其他問題可以解決這個問題,例如How to make CORS enabled requests in Angular 2

您應該理想的使用代理將您的請求轉發給API,最新的Angular CLI支持開箱即用代理(請參閱https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md)。你設置了一個proxy.conf.json可能看起來像這樣的:

{ "/api": { "target": "http://localhost:4040", "secure": false, "pathRewrite": {"^/api" : ""} } }

什麼這段代碼確實是從角到URI匹配的任何請求/ API將被轉發到本地主機:4040 。

請注意,您還需要弄清楚您的應用程序將如何在非開發環境中與API服務器交談。我很高興使用Nginx來爲Angular文件提供服務,並充當API的代理。

相關問題