Home > Enterprise >  Calling nodeJS HTTP server from Javascript
Calling nodeJS HTTP server from Javascript

Time:09-23

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);

CodePudding user response:

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')

CodePudding user response:

the URL handed to fetch function looks wronge, it would work if you adjust it to:

fetch('http://localhost:8081/?q=hi');

// or

fetch('/?q=hi');

it should work just fine, and ensure that you enable the cors if you need to works from any domain

CodePudding user response:

Every thing is fine, you just need to enable cors that's it, use the below code

const http = require('http')
const requestListener = function (req, res) {
    const headers = {
        'Access-Control-Allow-Origin': '*', /* @dev First, read about security */
        'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
        'Access-Control-Max-Age': 2592000, // 30 days
        /** add other headers as per requirement */
    };
    res.writeHead(200, headers);
    res.end(JSON.stringify({"key":"value"}));
}
const server = http.createServer(requestListener);
server.listen(8081);

If you are running both frontend and backend code on the same server then you don’t have to use complete url while if you are running fronted and backed on different server you need to enable cors and use complete url.

  • Related