Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch API and Cordova

I am having problems when using together Cordova and fetch API. I am executing the following code

fetch(BASE_URL + '/auth/login', {
  method: 'post',
  credentials: 'include',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: transformRequest({username: email, password: password})
}).then(response => {
      console.log(response.headers.get('X-AuthToken'))
});

When the code is executed in the browser the 'X-AuthToken' header is correctly retrieved and logged. When I run the same code when packaged in my Cordova app the 'X-AuthToken' header is null. Moreover what is strange is that i can see perfectly the header set when checking the response server side and when sniffing on the network so I am completely sure the header is there (simply it is not returned by the fetch API); in fact when using the equivalent XMLHttpRqeuest the header is correctly set:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", BASE_URL + /api/auth/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=username&password=password");
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       console.log (xhttp.getResponseHeader('X-AuthToken'));
    }
}

It is worth signaling that when I try to dump other common headers like pragma, cache-control, ... they are correctly logged. It seams like the fetch API is filtering the headers and removing the ones that are not standard. Is someone else experiencing the same problem? Am I missing something?

like image 772
pinturic Avatar asked Feb 22 '16 14:02

pinturic


People also ask

What is Cordova fetch?

This package can be used to install and uninstall Node. js packages using npm.

What is fetch API used for?

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

Is fetch API a REST API?

The Fetch API is a simpler, easy-to-use version of XMLHttpRequest to consume resources asynchronously. Fetch lets you work with REST APIs with additional options like caching data, reading streaming responses, and more. The major difference is that Fetch works with promises, not callbacks.

Is fetch API built in?

Now, JavaScript has its own built-in way to make API requests. This is the Fetch API, a new standard to make server requests with Promises, but which also includes additional features.


1 Answers

Nicely put question, you are developing on the cutting edge. I would stick to XMLHTTPRequest for now. Fetch api is not properly implemented in webkit. See webkit bugzilla bug 151937

like image 196
tnt-rox Avatar answered Oct 07 '22 02:10

tnt-rox