Handling Requests and Responses in Express
In Express, handling requests and sending responses are core functionalities. You can easily read request data such as body, query parameters, and headers, and send responses in different formats like JSON, HTML, or plain text.
Reading Request Data
You can access different parts of the incoming request using req (the request object).
app.post("/submit", (req, res) => { // Accessing request body const bodyData = req.body;
// Accessing query parameters const queryParam = req.query.term;
// Accessing headers const headerValue = req.headers["custom-header"];
res.send("Data received");});- Body:
req.bodycontains the parsed body of the request (requiresexpress.json()orexpress.urlencoded()middleware). - Query Parameters:
req.queryholds query parameters from the URL (e.g.,/search?term=express). - Headers:
req.headersprovides access to the request headers.
Sending Responses
Express provides various methods to send responses back to the client.
app.get("/json", (req, res) => { res.json({ message: "Hello, JSON!" }); // Sending JSON response});
app.get("/html", (req, res) => { res.send("<h1>Hello, HTML!</h1>"); // Sending HTML response});
app.get("/text", (req, res) => { res.send("Hello, plain text!"); // Sending plain text response});
app.get("/status", (req, res) => { res.status(404).send("Not Found"); // Sending response with status code});
// app.render()app.set("view engine", "ejs");
app.get("/", (req, res) => { res.render("index", { title: "Express App" }); // Rendering the 'index' view with dynamic data});res.json(): Sends a JSON response.res.send(): Sends a response of various types (string, object, buffer).res.render(): It is used to generate an HTML page by using a template and data. This requires a template engine like EJS, and it automatically replaces placeholders in the template with actual values.res.status(): Sets the HTTP status code of the response.