fetch Promise never gets executed

2019-07-06 08:21发布

问题:

I am using the nativescript to develop an app for android. I have something like

var fetchModule = require("fetch");
fetchModule.fetch("http://202.120.227.11/")
    .then(function(resp){
        console.log(JSON.stringify(resp));
        return resp;
    })
    .catch(function(err){
        console.log(JSON.stringify(err));
        return err;
    });

but the then block never gets executed. And sometimes the catch block gets executed and give a network error. But in either case, the request is sent and the response is smoothly received according to my tcpdump records.

So, it seems the nativescript has filtered the response for some reason.

Has anybody experienced that?

回答1:

Note that your resp is a Response object, if you want to read its contents you need to use one of its functions: arrayBuffer, blob, formData, json, or text.

These functions read the response to completion and return a promise that resolves with the read value.

For example,

fetch("http://202.120.227.11/")
.then(function(resp){
  return resp.json();
})
.then(function(val) {
  console.log(JSON.stringify(val));
  return val;
});


回答2:

I know this is super late, but I just wanted to post incase anyone comes across this same issue. I was encountering the same problem with NativeScript and my solution was to secure my site/endpoints. The App Transport Security policy requires the use of a secure connection. Therefore, http will not work. You must connect via https.