【问题标题】:load external JSON file using URL使用 URL 加载外部 JSON 文件
【发布时间】:2019-10-10 04:19:23
【问题描述】:

我在服务器上有一个JSON 文件。我想将它加载到我的angular-typescript 中。我尝试了以下方法。

ngOnInit () {
  this.httpService
    .get("http://x.x.x.x/config_files/test/config.json")
    .subscribe(data => console.log(data));
}

刷新页面时出现以下错误

从源“http://localhost:4200”访问“http://x.x.x.x/config_files/test/config.json”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

由于没有服务器端 API,因此无法添加标头 Access-Control-Allow-Origin。如何解决这个问题?

【问题讨论】:

标签: angular


【解决方案1】:

您可以使用某些插件来解决 CORS 问题,其中一个是 Moesif Origin & CORS Changer,提供的链接用于 chrome 扩展。

安装插件后,只需切换 ON 开关并刷新您的应用。 这个插件允许你发送跨域请求。您还可以覆盖 Request Origin 和 CORS 标头。

【讨论】:

    【解决方案2】:

    CORS 主要是后端问题。您可以在 Node.js 上使用以下代码解决它:

    var express = require('express');
    var app = express();
    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    

    但是如果你想在前端解决它,你可以在 Angular 中使用这种代码。将此代码放入 proxy.conf.json 中(但请注意,尾部斜杠足以使其不起作用):

    {
      "/config_files/*": {            <-- you may change this for config_files/test/
          "target": "http://xxxxxx:<port>",
          "secure": false,
          "logLevel": "debug",
          "changeOrigin": true
      }
    }
    

    package.json 中的以下内容:

    "scripts": {
        "ng": "ng",
        "start": "ng serve --proxy-config proxy.conf.json",
        ...
    }
    

    并在 angular.json 中添加代理配置:

    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "event:build",
        "proxyConfig": "proxy.conf.json"  <-- this line
      },...
    

    npm start 开头。

    它应该适用于您的情况,但在其他情况下(当然不是在 prod 中),我发现临时使用 ChromeFirefox 的扩展名更容易。 我还发现,由于某些限制,它可能无法在 Chromium 和 Chrome Canary 中运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多