本地托管API无法从Angular 4访问http

问题描述:

我有一个很奇怪的问题。本地托管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: *'); - 相同的行为

对不起,我的坏。解决方案很简单:

请求中的“缓存控制”标题似乎不被允许,尽管在用邮差测试api时它工作正常。 我从请求中删除标题,一切运行良好。

+0

使用cors中间件,您不会考虑OPTIONS预检请求 – charlietfl

由于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的代理。