create a http server with a get route in javascript

To create a simple HTTP server with a GET route in JavaScript using Node.js, you can use the built-in http module. Here's an example:

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

const server = http.createServer((req, res) => {
  if (req.url === '/hello') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, world!\n');
  } else {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/plain');
    res.end('404 Not Found\n');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
435 chars
18 lines

In this example, we're creating an HTTP server that listens on port 3000. When a request is made to http://localhost:3000/hello, the server responds with a 200 OK status code and the message 'Hello, world!'. For any other URL, the server responds with a 404 Not Found status code.

You can test the server by running it with node and accessing http://localhost:3000/hello in your web browser or using a tool like curl.

gistlibby LogSnag