Angular - 仅协议方案支持跨源请求 - 需要解决方法才能在本地运行$http

Angular - Cross origin requests are only supported for protocol schemes - need workaround to run $http in local

本文关键字:方法 http 运行 解决 方案 协议 支持 请求 Angular      更新时间:2023-09-26

已经浏览了许多论坛,甚至在stackoverflow中也为以下错误提供了解决方法:XMLHttpRequest无法加载 file:///...。跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https、chrome-extension-resource。

尽管有使用 Node.js 之类的解决方案,但应用程序和源代码需要托管在 http 服务器中,但我需要一个解决方法,以便我可以在本地测试我的 $http get()。

我也尝试过,用 --allow-file-access-from-files --disable-web-security 开始 chrome,但没有运气。

那么,任何人都可以帮助我在没有服务器的情况下在本地运行我的$http get()吗?还是必须使用服务器?

下面是我的代码。

app.factory('jsonFactory', function($http) { 
var obj = {};
$http.get("response.json").then(function (response) {
    obj = response.data;
});
return {
    get: function () {
        return obj;
    }
};});

尝试使用纯 JavaScript 文件阅读器

function readSingleFile(e) {
  var file = e.target.files[0];
  if (!file) {
    return;
  }
  var reader = new FileReader();
  reader.onload = function(e) {
    var contents = e.target.result;
    displayContents(contents);
  };
  reader.readAsText(file);
}
function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.innerHTML = contents;
}
document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>

请参阅代码段 @如何使用 Javascript 打开本地磁盘文件?。

要知道它在角度应用程序内看起来很糟糕。 没有项目经理会强制执行这样的要求。