skip to Main Content

Hey guys, need some help if possible-

I have a webpage and an express server. All works okay on my laptop using touchscreen. The issue is, when I run a live server and access the webpage through my phone, it seems like the server requests just don’t happen. I have added CORS origin to my devices IP and configured the event listener so it takes touch events. Is there something else I’m missing?

Server:

const express = require('express');
const app = express();
const cors = require('cors');
const PORT = 4001;

app.use(cors({ origin: ['vscode IP and port', 'MY phones IP'] }));

app.get('/test', (req, res, next) => {
    res.send({ test: 'testing' });
});

app.listen(PORT, (req, res, next) => {
    console.log(`Runnning on port: ${PORT}`);
})

JS:

const h1 = document.querySelector('#testh1');
const p = document.querySelector('p');

h1.addEventListener('touchstart', async () => {
    const response = await fetch('http://localhost:4001/test');
    const jsonResponse = await response.json();
    p.innerHTML = jsonResponse.test
});

Any help is appreciated, thanks

This is just a test before I implement into my actual project.

The webpage has a button which you click, Then it displays the object value from the response.

Works fine on my laptop where it is running but not from my phone

2

Answers


  1. The issue here is with localhost. Localhost will ONLY be accessible from your laptop because it is technically the laptops internal network. This is also true for the phone, so referencing localhost never actually reaches outside the device.

    Your phone has no way to connect to it. One solution is to tunnel localhost out to the public internet using ngrok: https://ngrok.com/

    install ngrok, then do ngrok http http://localhost:<yourt-port>, this will then give you back a public address you can use. Be aware, this is a PUBLIC web address, so be sure to not expose any sensitive data. Also the address will change every time the tunnel is restarted.

    UPDATE Method #2 (from Keith):

    You can also connect to the server running on your laptop (provided they are on the same network) by updating the URL on the phone to be http://:/test

    Be aware that if you have any sort of firewall configured (particularly on windows) it may block this connection.

    Login or Signup to reply.
  2. I am going to elaborate a bit more on what @tevemadar says… When you run your node server on your laptop, localhost is local to the machine you’re running that server on. Trying to access the same localhost from your phone as you do on your laptop is not going to happen from that sense.

    If youre wanting to access the laptop localhost from another device you can use a tool like ngrok.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search