How can I access my localhost from my Android device?

前端 未结 30 3006
面向向阳花
面向向阳花 2020-11-21 05:53

I\'m able to access my laptop web server using the Android emulator, I\'m using 10.0.2.2:portno works well.

But when I connect my real Android phone, th

30条回答
  •  佛祖请我去吃肉
    2020-11-21 06:35

    Mac OS X users

    I achieved this by enabling remote management:

    • Ensure that your phone and laptop are connected to the same WiFi network
    • On Mac, go to System preferences/sharing
    • Enable remote management

    You will see a message similar to this:

    • Other users can manage your computer using the address some.url.com

    On your Android device, you should now be able to go to some.url.com, which delegates to localhost on your Mac. You can also use ifconfig to get the IP address of your Mac.


    Portable solution with ngrok (any OS with Node.js)

    If you don't mind exposing your project with a temporary domain you can use ngrok. Lets say I have an app that runs on localhost:9460 I can simply write

    npm install ngrok -g
    
    ngrok http 9460
    

    This will give me:

    Session Status                online
    Update                        update available (version 2.2.8, Ctrl-U to update)
    Version                       2.2.3
    Region                        United States (us)
    Web Interface                 http://127.0.0.1:4040
    Forwarding                    http://f7c23d14.ngrok.io -> localhost:9460
    Forwarding                    https://f7c23d14.ngrok.io -> localhost:9460
    
    Connections                   ttl     opn     rt1     rt5     p50     p90
                                  0       0       0.00    0.00    0.00    0.00
    

    I can now reach https://f7c23d14.ngrok.io as a way to remotely view localhost. This is great to share design work or progress with clients.


    Alternate solution with nginx proxy pass

    If you are running something like this through nginx proxy_pass it will require a bit more tweaking - this is a hacky approach, but it works for me and I am open to suggestions on improving it:

    • Enable remote management (as mentioned above)
    • Temporarily set the server to listen on port 81 as opposed to 80
    • Type in the following command:
    sudo nginx -s reload
    
    • Visit http://youripaddress:81
    server {
      listen 80;
      listen 81;   # <-------- add this to expose the app on a unique port
      server_name  ~^(local|local\.m).example.com$;
      # ...
    }
    

    Reload and visit http://youripaddress:81

提交回复
热议问题