devnotes.

Express HTTP methods

HTTP methods tell the server what kind of operation to perform on a resource — fetch it, create it, replace it, or remove it. Express maps each method to its own routing function.

GET

Fetches data from the server.

app.get("/products", (req, res) => {
    res.send("List of products");
});

POST

Sends data to the server, usually to create something.

app.post("/products", (req, res) => {
    res.send("Product created");
});

PUT

Replaces an existing resource with new data.

app.put("/products/:id", (req, res) => {
    res.send(`Product ${req.params.id} fully updated`);
});

DELETE

Removes a resource.

app.delete("/products/:id", (req, res) => {
    res.send(`Product ${req.params.id} removed`);
});

PATCH

Applies a partial update to a resource.

app.patch("/products/:id", (req, res) => {
    res.send(`Product ${req.params.id} partially updated`);
});

Putting it together

const express = require("express");
const app = express();
const PORT = 5000;

app.use(express.json());

app.get("/", (req, res) => res.send("Inventory Service"));
app.post("/products", (req, res) => res.send("Product created"));
app.put("/products/:id", (req, res) => res.send(`Product ${req.params.id} updated`));
app.delete("/products/:id", (req, res) => res.send(`Product ${req.params.id} deleted`));

app.listen(PORT, () => console.log(`Listening on ${PORT}`));

Extra response helpers

MethodDescription
res.download()Prompts a file download.
res.redirect()Redirects the client to a different URL.
res.render()Renders a view template.
res.sendFile()Sends a file.
res.sendStatus()Sets the status code and sends its text as the body.
res.end()Ends the response manually.
res.json()Sends a JSON response.
res.jsonp()Sends JSON with JSONP support.
Express HTTP methods | DevNotes