#StackBounty: #react-native #webview #fetch Correct way to fetch JSON with React Native's WebView

Bounty: 150

It seems WebView plays a similar role of service workers for react-native.

I am trying to offload heavy data fetch to a WebView but it seems very painful and could not find a fetch example with WebView.

So I have below JavaScript code with which I am trying to call the API.

When using the exact same code from a regular react-native class, the JSON response is perfectly fetched and parsed.

But when the same JavaScript code is injected into a WebView with injectJavaScript method, the Content-Type value causes the problem. (When I remove it, I see from the backend that the call is made but I can not get the JSON data at the frontend – WebView side-.)

It seems it is related to cors even though the API backend allows all cross-origin requests.

As a result, my questions are:

  1. What is a proper way to use fetch with WebView in react-native?
  2. Why the behaviour is different between react-native and WebView?
var l_headers = {
   Accept: 'application/json',
   'Content-Type': 'application/json'
};
var l_init = {
    method: "POST",
    headers: l_headers,
    body: {}
};
fetch("http://172.20.10.12:8000/test", l_init).then(function (response) {
    return response.json();
}).then(function (responseJson) {
    alert('API called: ' + JSON.stringify(responseJson));
});

PS: One final handicap, please note that I am also using EXPO and not able to eject because of its benefits. That is why I can not use react-native-community’s react-native-webview as of today. (It seems in future this will be adapted for EXPO).


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.