Search code examples
javascriptreactjswebpackfetchpolyfills

React fetch polyfill on mobile devices not working


Trying to get fetch to work on ios/android (chrome & safari). I currently have this in my webpack (using webpack 4):

new webpack.ProvidePlugin({
   Promise: 'imports-loader?this=>global!exports-loader?global.Promise!es6-promise',
   fetch: 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
}),

With this code it works for IE desktop, but on my android it gives the following error:

Uncaught (in promise) TypeError: Failed to fetch

The fetch code:

fetch('http://localhost:8092/api/shops/search?searchString=spicy')
    .then(function(response) {
        if (response.status >= 400) {
            throw new Error("Bad response from server");
        }
        return response.json();
    })
    .then(function(stories) {
        console.log('hej', stories);
    });

Any ideas?


Solution

  • It's because your http://localhost:8092 is correctly resolved while on your desktop (assume to 127.0.0.1), but for your mobile device - localhost is this particular device, not your desktop. So I guess you should try to use ip address which can be accessible through all of your network (instead of just localhost), assuming your mobile device is connected to the same one.