Dair
Dair

Reputation: 16240

Can't connect to localhost in React Native WebView

I started up a simple http server (from here):

from wsgiref.simple_server import make_server

def app(environ, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    yield b"<h1>Goodbye, World!</h1>"

server = make_server('127.0.0.1', 8080, app)
server.serve_forever()

Ran it using:

python3 simple_serve.py

Redirecting to http://127.0.0.1:8080/ displays "Goodbye, World!".

I then created a new React Native Project and changed index.android.js to:

import React, { Component } from 'react';
import {
  AppRegistry,
  WebView,
} from 'react-native';

export default class WebTest extends Component {
  render() {
    return (
      <WebView
        source= {{ uri: "http://127.0.0.1:8080/" }}
      />
    );
  }
}

AppRegistry.registerComponent('WebTest', () => WebTest);

"Goodbye, World!" doesn't show up, and I get a warning that says:

Encountered an error loading page {"canGoForward"false,"code":-6,"canGoBack":false,"description":"net::ERR_CONNECTION_REFUSED","loading":false,"title":"","url":"http://127.0.0.1:8080/","target":5}

For reference, changing http://127.0.0.1:8080/ to https://www.google.com works.

Upvotes: 8

Views: 18018

Answers (6)

FedICE
FedICE

Reputation: 1

There is a possibility of failure when attempting to send requests to your own WiFi IP address, depending on the network configuration. If other solutions in this question have been unsuccessful, you can consider trying the approach I propose.

By utilizing tools like ngrok, you can expose your localhost server to an external IP address and subsequently send requests to that IP from your React Native application.

Upvotes: 0

AKIN KARAYUN
AKIN KARAYUN

Reputation: 29

use it like that http://10.0.2.2://your port num this will work definetly

Upvotes: 2

mdehghani
mdehghani

Reputation: 551

I'm using a mac and i found the proper ip address in the network settings: enter image description here

Upvotes: 2

Blaze Gawlik
Blaze Gawlik

Reputation: 347

I was able to connect to localhost by finding my computer's IP Address. Open cmd prompt and type this for mac:

ifconfig | grep inet

Windows:

ipconfig/ALL

mine was listed between inet & netmask exhttp://194.178.1.2:4242/ and as Webview uri worked fine

Upvotes: 0

I had success doing :

adb reverse tcp:3000 tcp:3000

My webview:

<WebView source={{uri: 'http://localhost:3000'}} ... 

Upvotes: 25

Saravana Kumar
Saravana Kumar

Reputation: 3396

Use that IP 10.0.2.2 instead of 127.0.0.1

Upvotes: 19

Related Questions