Node.js
app.post
Learn to define POST routes with app.post.
app.post
app.post(path, handler) defines a POST route. It works like app.get but listens for POST requests. POST is usually used to submit data (forms, APIs).
To read the POST request's body you use req.body. But Express does not parse the body by default; you must add the JSON middleware with app.use(express.json()). Example: app.post("/data", (req, res) => { res.json({ received: req.body.name }); });. Here req.body.name reads the sent name value. res.json sends an object as a JSON response; the content type is automatically application/json.
req.body and express.json()
The POST request's body is read with req.body. But Express does not parse it by default. For a JSON body you add the app.use(express.json()) middleware.
Example: app.use(express.json()); app.post("/data", (req, res) => { console.log(req.body); res.json({ received: req.body.name }); });. When the client sends { "name": "Alex" }, req.body.name becomes Alex. The express.json() middleware turns the incoming JSON string into an object and puts it on req.body. Without it req.body is undefined. A middleware is a function that runs between the request and the route.
Exercise Define a POST route
Import express and create app. Add the JSON middleware with app.use(express.json()). Define a POST route with app.post("/data", (req, res) => res.json({ received: req.body.name })). The ready-made code below starts the server and sends a POST request with body { name: "Alex" }.
Show example solution
const express = require("express");
const app = express();
app.use(express.json());
app.post("/data", (req, res) => { res.json({ received: req.body.name }); });
const server = app.listen(3000, () => {
const http = require("http");
const opts = { hostname: "localhost", port: 3000, path: "/data", method: "POST", headers: { "Content-Type": "application/json" } };
const r = http.request(opts, (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
r.write(JSON.stringify({ name: "Alex" }));
r.end();
});
Test yourself
-
What is app.post used for?
app.post("/data", handler)
- GET isteklerini dinler
- Closes the server
- POST isteklerini dinler
- Loads the module
Show answer
POST isteklerini dinler — app.post listens for POST requests.
-
Match each piece to its role
- app.post
- Defines a POST route
- req.body
- Reads the body
- express.json()
- Parses the body
- res.json
- Sends a JSON response
-
Complete the req.body access
res.json({ alindi: req.____.ad });
Show answer
res.json({ alindi: req.body.ad });
Next lesson: app.listen