Search code examples
javascriptnode.jsfetch-apihttpserver

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

  • 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.