localhost

时间:2018-02-21 11:58:52

标签: cors localhost angular-http

我倾向于Angular,尝试使用HTTP获取我的PC上的文件。我想模拟服务器场景,因此尝试使用以下内容(live-server,browser-sync& xampp)一次提供服务,但每次尝试都会收到错误

  

无法加载http://localhost/ng-data/products.json:' Access-Control-Allow-Origin'标头的值为' http://localhost:4200/'这不等于提供的原产地。起源' http://localhost:4200'因此不允许访问

当我在网址中粘贴网址(http://localhost/ng-data/products.json)时,我可以获取该文件。

2 个答案:

答案 0 :(得分:2)

我找到了解决这种情况的其他两种方法,

解决方案1:

要将products.json文件更改为products.php,请在顶部添加:

<?php  
  'header(Access-Control-Allow-Origin: *)';
  'header(Content-Type: application/json)'
?>  

最后,更改您要连接的网址,从products.json更改为products.php

解决方案2

使用代理配置请参阅:Angular documentatiom

按照以下步骤操作:

1-将服务中的网址更改为'/ api / products'而不是'http://localhost/products'

2-在angular项目的根目录中创建proxy.config.json文件 在其中添加此代码:

    {
  "/api/*": {
    "target": "http://localhost",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

3-在服务器上创建文件夹api并在其中添加products.json。

注意:在我的情况下,我使用的是localhost,没有指定端口,因为我正在使用xampp。但是,如果您使用节点,例如,您将在proxy.config.json

中指定类似:localhost:3000的端口

答案 1 :(得分:-3)

由于您正在测试,我建议您使用Chrome扩展程序。请在Chrome扩展程序列表中搜索此内容,如下所示,然后启用它。可能你的问题会得到解决。

enter image description here