create a http server with a delete route in typescript

Here's an example of how you can create a simple HTTP server with a DELETE route using TypeScript:

index.ts
import * as http from 'http';

const server = http.createServer((req, res) => {
  if (req.method === 'DELETE') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Deleted!');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Route not found');
  }
});

server.listen(8080, () => {
  console.log('Server started on port 8080');
});
384 chars
16 lines

Explanation:

  • We import the http module, which we'll use to create the server.
  • We create a new server using the createServer() method of the http module. This method takes a callback function that will be executed on every request the server receives.
  • Inside the callback function, we check if the incoming request method is DELETE. If it is, we return a 200 status code with the message Deleted!. Otherwise, we return a 404 status code with the message Route not found.
  • Lastly, we tell the server to listen on port 8080 using the listen() method, and we log a message when the server starts.

Note:

  • This is just a basic example to showcase how to create a DELETE route, you'll likely need to modify the logic inside the callback function to suit your needs.
  • Be careful when using DELETE requests - make sure to implement proper authentication and validation to prevent accidental or malicious data loss.

gistlibby LogSnag