首页 文章

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

提问于
浏览
-1

我有一个非常奇怪的问题 .

  • 使用XAMPP本地托管的PHP Slim App(localhost:4040)

  • 本地托管Angular 4应用程序使用CLI(localhost:4200)

使用"Postman"和浏览器进行API请求没问题,一切正常 . 现在我正在使用 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:对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头 . 因此不允许来源'http:// localhost:4200'访问 .

但是:我肯定会发送这些 Headers !

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;
}

我已经尝试解决的问题:

  • 在Docker容器中运行Slim App以获得与localhost不同的原点 - 相同的行为

  • 在index.php的顶部添加allow-origin-header
    header('Access-Control-Allow-Origin: *'); - 同样的行为

2 回答

  • 0

    对不起这是我的错 . 解决方案很简单:

    似乎不允许请求中的“Cache-control”标头,尽管在使用Postman测试api时它工作正常 . 我从请求中删除了 Headers ,一切运行良好 .

  • 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" : ""} } }

    这段代码的作用是从Angular到URI匹配/ api的任何请求都将被转发到localhost:4040 .

    请注意,您还需要弄清楚您的应用在非开发环境中如何与API服务器通信 . 我很高兴使用Nginx来提供Angular文件,并充当API的代理 .

相关问题