hhsb
hhsb

Reputation: 582

Parsing json in gz files from a local directory through ajax - angularJS

I am trying to read a json present in data.gz using angularJS's $http service. But I only get strange symbols and characters as a response. I am currently running the app locally in a nodeJS server. Am I missing something in here?

$http({ 
  url: 'systemRes.10.gz',
  method: 'GET'
})
.then(function successCallback(response) {
  console.log(response.data); //shows strange characters
});

Click to view the strange characters.

Since , the file is in a local directory , setting headers to the following causes an error : Refused to set unsafe header "Accept-Encoding"

headers: { 'Accept-Encoding': 'gzip' }

Upvotes: 3

Views: 1157

Answers (1)

Jordan Quagliatini
Jordan Quagliatini

Reputation: 193

Trying to access a local gz file will not provide the Content-Encoding header which is mandatory for the browser to unzip the file.

This is confirmed by this previous post -> Angular gunzip json file automatically : Refused to set unsafe header "Accept-Encoding"

You should try to serve your file with a proper file server like nginx or apache, if you need to use your js file in production. Otherwise if it is for a one-time script you should consider using http-server, which provide the -g option, serving your gzipped version of the file. For example, if your file is systemRes.10.json.gz then by launching http-server in your folder with

$ npm i http-server
$ node_modules/.bin/http-server -g

You could write the following js script (with fetch, but $http behaviour should be identical)

fetch('http://localhost:8080/systemRes.10.json')
  .then(resp => resp.json())
  .then(json => console.log(json))
  .catch(e => console.error(e))

I tested it and it provides the Content-Encoding header, so you should be good for your tests.

Upvotes: 1

Related Questions