1

had gone through many forums, even in stackoverflow for a workaround for the error: XMLHttpRequest cannot load file:///.... Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Though there are solutions like using Node.js, app and source needs to be hosted in a http server, I need a workaround so that I could test my $http get() in local.

I have also tried, starting chrome with --allow-file-access-from-files --disable-web-security, but no luck.

So, can any one help me running my $http get() in local without server? Or is it mandatory to go for a server?

Below is my code.

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

1 Answers1

1

Try with a pure javascript filereader

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>

see snippet @ How to open a local disk file with Javascript?.

Know that it looks terrible inside an angular app. No project manager would enforce such requirement.

Community
  • 1
  • 1
gyc
  • 4,300
  • 5
  • 32
  • 54
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/12909168) – Jonathan Argentiero Jul 05 '16 at 12:23
  • 1
    @JonathanArgentiero, right I added the snippet to the answer but being downvoted repeatedly for answering a question doesn't motivate me to answer more questions or to even keep this answer live. I prefer leaving the question unanswered... – gyc Jul 05 '16 at 12:31
  • 1
    @gyc, anyways your answer provided me a solution. Wee, I would parse the "contents" to Json and would bind it to the view.Thanks !. Be motivated! :-) – Suresh PMS Jul 06 '16 at 09:48