Nativescript: Angular 2 + NativeScript Response with status: 200 for URL: null (GZIP Compressed endpoint)

Created on 17 Feb 2017  Â·  8Comments  Â·  Source: NativeScript/NativeScript

Please, provide the details below:

Did you verify this is a real problem by searching Stack Overflow and the other open issues in this repo?

I don't found no answers for my problem

Tell us about the problem

Problem with HTTP REQUEST in nativescript app, returning:
Response with status: 200 for URL: null
{"_body":{},"status":200,"ok":true,"statusText":"","headers":{},"type":3,"url":null}
SyntaxError: Unexpected token � in JSON at position 0

Which platform(s) does your issue occur on?

Android

Please provide the following version numbers that your issue occurs with:

  • CLI: 2.5.0

I'm getting this error when trying to do a POST.

Response with status: 200 for URL: null
* {"_body":{},"status":200,"ok":true,"statusText":"","headers":{},"type":3,"url":null} *

This is my code

import { Injectable } from "@angular/core";
import { Http, Headers } from "@angular/http";
import "rxjs/Rx";

let LocalStorage = require( "nativescript-localstorage" );

import { User } from "../";
import { BackendService, Package, Pack, Order, Address, Reason } from "../";

@Injectable()
export class PackageService {
  public constructor(private http: Http) { }
  token : string = LocalStorage.getItem('token');
  userId : number = LocalStorage.getItem('userId');

  getPackages() {
    let headers = new Headers();
    let url = BackendService.apiUrl + BackendService.apiNameSpace + "mobile/packinglist/list";
    headers.append("Content-Type", "application/json");
    headers.append("Authorization", "Bearer " + this.token);
    this.http.post(url, {userId: this.userId}, { headers: headers})
      .map(result => JSON.parse(result.json()))
      .do(result => console.log("RESULT: ", JSON.stringify(result)))
      .subscribe(result => {
          //TODO
      }, error => {
          console.log("ERROR: ", error);
      });
  }
}

and my packages.config

{
  "description": "FM Transportes",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "FM Transportes",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "org.nativescript.FMTransportes",
    "tns-android": {
      "version": "2.5.0"
    }
  },
  "dependencies": {
    "@angular/common": "2.2.1",
    "@angular/compiler": "2.2.1",
    "@angular/core": "2.2.1",
    "@angular/forms": "2.2.1",
    "@angular/http": "2.2.1",
    "@angular/platform-browser": "2.2.1",
    "@angular/platform-browser-dynamic": "2.2.1",
    "@angular/router": "3.2.1",
    "email-validator": "1.0.4",
    "nativescript-angular": "1.2.0",
    "nativescript-localstorage": "^1.1.0",
    "nativescript-sqlite": "^1.1.2",
    "nativescript-telerik-ui": "^1.5.1",
    "nativescript-theme-core": "^0.2.1",
    "reflect-metadata": "~0.1.8",
    "rxjs": "5.0.0-beta.12",
    "tns-core-modules": "2.3.0"
  },
  "devDependencies": {
    "babel-traverse": "6.18.0",
    "babel-types": "6.18.0",
    "babylon": "6.13.1",
    "lazy": "1.0.11",
    "nativescript-dev-typescript": "^0.3.2",
    "typescript": "^2.0.8",
    "zone.js": "~0.6.21"
  }
}

*UPDATE*
I've tried to use the nativescript http component to do the request (https://docs.nativescript.org/cookbook/http) but occurred an other error while trying to parse to JSON:

Uncaught (in promise): SyntaxError: Unexpected token � in JSON at position 0

i console.log the response before JSON.stringfy and the result was:

enter image description here

I tryied the same request at postman and the response was correct.

EDIT
I tried with javascript XMLHttpRequest

var request = new XMLHttpRequest();
    request.open('POST', "http://api.alfatracking.com.br/homolog/api/v1/mobile/packinglist/list", true);
    request.setRequestHeader('Authorization', "Bearer ...thetoken...");
    request.setRequestHeader('Content-Type', 'application/json');
    request.send(JSON.stringify({userId: "4f235762-d0f2-e611-901e-002197e04fb6"}));

    request.onreadystatechange = () => {
      console.log("finished");
      console.log(request.readyState);
      console.log(request.responseText);
      console.log(request.responseType);

and the response was the following:
enter image description here

but on web browser the same code works.
enter image description here

question

All 8 comments

I found the problem. The response of API that i'm requesting was compressed in GZIP.
Is there a way to accept GZIP encoding in nativescript?

@dzfweb

Indeed the GZIP encoding is not supported at this very moment by the http module. Discussion about this feature can be found here.

As a workaround, you can try to replace the http module with nativescript-okhttp plugin,

related to #1314

you can use nativescript http with angular , following example:

first import http serves in the top of the service component
var http = require("http");

in the sevice.ts file ,you need to convert the http promise to observable .

//GET Example
    getList(): Observable<News[]> {
        return Observable.fromPromise(
                    **http.getJSON(serverConfig.apiUrl+"news")**
                ).map(function(res:any) {
                    console.log('finished sendign request'); 
                    return res as News[] 
                } );

    }


//POST EXAMPLE

submitFormData(data): Observable<Forms> {
        let url:string=serverConfig.apiUrl+"forms/";
        let headers:any = { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this.appSettings.getString("access_token")};
        let req:any={
            url:url,
            method: "post",
            headers:headers,
            content: JSON.stringify(data)
        };

        return Observable.fromPromise(
                    http.getJSON(req)
                ).map(function(res:any) {
                    return res as Forms 
                } );
    }

then you can subscribe to the observeable as you used befor,

        this.newsService.getList().subscribe((res) => {
            this.news= res;
        });

Note : now you can remove the import statment of angular http since its not needed

some ideia of when GZIP will be supported?

Hi @dzfweb,
This feature request is still under review and unfortunately, I can not commit to the exact time frame, when this will be implemented. This feature could be expected for some of the next NativeScript version after 3.0 release.
You could keep track on the issue here for further info.
Regarding that, you could also review the @mshanak workaround and to verify whether this is applicable for you.

I had this problem too. It wasn't anything about gzip compression. It was something about my server, the SSL was bad configured. I made a console.dump of the error and saw that I was getting an exception with something about the SSL Handshake:

Error: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

This was caused by not having a installed all intermediate certificates on my certificate file. This site helped: https://certificatechain.io/

Hope this helps somebody.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Leo-lay picture Leo-lay  Â·  3Comments

nirsalon picture nirsalon  Â·  3Comments

rLoka picture rLoka  Â·  3Comments

valentinstoychev picture valentinstoychev  Â·  3Comments

OscarLopezArnaiz picture OscarLopezArnaiz  Â·  3Comments