create a http server with a delete route in javascript

To create an HTTP server with a delete route in JavaScript, we can use the express.js framework. Follow these steps:

  1. Install the express.js and http-server packages using npm:
npm install express http-server
32 chars
2 lines
  1. Import the necessary packages and create an instance of Express:
index.tsx
const express = require('express');
const app = express();
59 chars
3 lines
  1. Define a delete route using the .delete() method:
index.tsx
app.delete('/delete/:id', (req, res) => {
  const id = req.params.id;
  // Code to delete the resource with the given ID
  res.send(`Deleted resource with ID ${id}`);
});
171 chars
6 lines

This route will listen for requests that use the DELETE method and have a URL parameter id in the format /delete/:id.

  1. Start the HTTP server using Express' .listen() method:
index.tsx
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});
99 chars
5 lines

Now when the server is started with node server.js, it will listen for incoming requests at http://localhost:3000. To delete a resource, send a DELETE request to http://localhost:3000/delete/<id>, where <id> is the ID of the resource to be deleted.

gistlibby LogSnag