create a http server with a custom route in javascript

To create a custom HTTP server with a custom route in JavaScript using Node.js, follow these steps:

  1. First, create a new Node.js project in your preferred directory on your machine

  2. In your project directory, create a new file called server.js

  3. Import the http module and create a new HTTP server

index.tsx
const http = require('http');

const server = http.createServer((req, res) => {
  // handle request
});
104 chars
6 lines
  1. Next, define your custom route and specify its response
index.tsx
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/custom-route') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('This is a custom route');
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Page not found');
  }
});
318 chars
12 lines
  1. Start the server and listen on a specified port
index.tsx
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/custom-route') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('This is a custom route');
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Page not found');
  }
});

server.listen(3000, () => {
  console.log('Server is running on port 3000');
});
400 chars
16 lines
  1. Run the program by typing node server.js in the terminal

  2. Visit http://localhost:3000/custom-route in your web browser to see the custom route being served by your HTTP server

Congratulations! You have just created a custom HTTP server with a custom route in JavaScript.

gistlibby LogSnag