create a http server with a specific route in javascript

To create an HTTP server with a specific route in JavaScript, you can use the built-in Node.js http module and create a Server object. Here's an example:

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

const server = http.createServer((req, res) => {
  if (req.url === '/mypage') {  // specify your route
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<h1>Hello World!</h1>');
    res.end();
  } else {
    res.writeHead(404, {'Content-Type': 'text/html'});
    res.write('404 Not Found');
    res.end();
  }
});

server.listen(3000);  // listen on port 3000
411 chars
16 lines

In this example, we create a server and specify the route /mypage. When a client requests this route, the server sends a response with a 200 status code and the string <h1>Hello World!</h1> as the HTTP response body. For any other route, the server sends a 404 Not Found response.

You can modify this code to create as many routes as you need by adding more if statements inside the callback function of createServer.

gistlibby LogSnag