create a http server with a specific route and a specific status code in javascript

To create a HTTP server with a specific route and a specific status code, you can use Node.js built-in http module. Here is an example:

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

const PORT = 3000;

const server = http.createServer((req, res) => {
  if (req.url === '/foo') {
    res.writeHead(200, { 'Content-Type': 'text/plain' }); // set response status code and headers
    res.end('Hello, foo!'); // send response body
  } else {
    res.writeHead(404); // set response status code
    res.end(); // send empty response body
  }
});

server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
472 chars
18 lines

In the above code, we create a HTTP server that listens on port 3000. The server has a single route /foo. If the requested URL is /foo, the server responds with a 200 OK status code and Hello, foo! message. Otherwise, the server responds with a 404 Not Found status code and an empty response body.

You can test the server by opening a web browser and navigating to http://localhost:3000/foo. You should see the message Hello, foo! displayed on the page. If you navigate to another URL, you should see a 404 Not Found error.

gistlibby LogSnag