Calling nodeJS HTTP server from Javascript

I am trying to setup a very simple nodeJS HTTP server. When I call it from the browser, like this http://localhost:8081, it works fine, but when I call is using a JS fetch() method, I get a 404 error:

GET http://localhost/:8081?q=hi

JS:

fetch(":8081/?q=hi")

NODE JS:

const requestListener = function (req, res) {
  res.writeHead(200);
  res.end('Hello, World!');
  }
const server = http.createServer(requestListener);
server.listen(8081);

>Solution :

When you’re calling your local server through JS fetch, you don’t need to add the port number you can call it like below:

fetch('/?q=hi')

Leave a Reply