Home > Mobile >  GET request from local server using live-server
GET request from local server using live-server

Time:02-13

I am trying to fetch data from my local server and here is my server and how I handled GET requests:

const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());

app.listen(port, () => {
  console.log(`app running on port: ${port}...`);
});

const responseToClient = (req, res) => {
  res.status(200).json({
    status: 'success',
    body: 'Hello from the server!',
  });
};

app.get('/api', responseToClient);

When I run my server and send a GET request to this address: 127.0.0.1:3000/api with Postman, it works perfectly.

The thing is I created a html page along with a js file and want to fetch data from my local server by it. Here is my fetch request on my js file:

const url = '/api';

const fetchData = async () => {
  try {
    const response = await fetch(url);
    const body = await response.json();
    alert(body);
  } catch (error) {
    alert(error);
  }
};
fetchData();

I run my html file with live-server (extension) which runs on port 5500 by default , so the address my fetch request goes to will be 127.0.0.1:5500/api (instead of 127.0.0.1:3000/api), so it does not exists and I get an error message.

I tried to change the port of my server and set it to 5500 (the same as live-server) but it did not work.

How can I run my local server and send requests to it with live-server and my html file?

CodePudding user response:

If you do not want to have the HTML and JS files static-ed onto your Express server, then try this:

const url = '/api'; // bad
const url = '127.0.0.1:3000/api'; // better

CodePudding user response:

Solved by using

 const url = 'http://localhost:3000/api';

instead of ip address and installing cors middle ware.

  • Related