Topic 001: express, cors, body parser packages
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It is the de facto standard server framework for Node.js and is known for its simplicity and performance.
- Routing: Express provides a powerful routing mechanism that allows you to define routes for different HTTP methods and URL paths.
- Middleware: Express middleware are functions that execute during the lifecycle of a request to the server. Middleware can modify the request and response objects, end the request-response cycle, or call the next middleware in the stack.
- Templating: Express supports various templating engines (like Pug, EJS, Handlebars) to generate HTML dynamically.
- Error Handling: Express has a built-in error-handling mechanism that allows you to handle errors in a centralized place.
- Static Files: It provides a middleware to serve static files such as images, CSS files, and JavaScript files.
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});CORS is a security feature implemented by browsers to control how resources on a web page can be requested from another domain outside the domain from which the resource originated. The cors package for Express is a middleware that enables CORS with various options.
- Simple Configuration: Allows you to easily enable CORS with various configurations.
- Pre-Flight Requests: Manages pre-flight requests automatically.
- Custom Headers: Allows you to specify custom headers to be exposed.
- Credentialed Requests: Supports sending credentials like cookies and HTTP authentication.
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.get("/data", (req, res) => {
res.json({ message: "This is CORS-enabled for all origins!" });
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});const corsOptions = {
origin: "http://example.com",
methods: "GET,POST",
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
optionsSuccessStatus: 204,
};
app.use(cors(corsOptions));Body-Parser is a middleware for parsing incoming request bodies in a middleware before your handlers, available under the req.body property. It parses incoming request bodies in a middleware and makes the parsed data available on req.body.
- JSON Parsing: Parses
application/jsontype bodies. - URL-Encoded Data Parsing: Parses
application/x-www-form-urlencodedtype bodies. - Raw and Text Parsing: Can parse
application/octet-streamandtext/plaintype bodies.
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/submit", (req, res) => {
console.log(req.body);
res.send("Data received");
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});app.use(
bodyParser.json({
limit: "10mb", // Limit the size of the JSON payload
strict: true, // Only accept arrays and objects
type: "application/json",
})
);
app.use(
bodyParser.urlencoded({
extended: true, // Use extended syntax for rich objects and arrays
parameterLimit: 10000, // Limit the number of parameters
})
);These three packages—Express, CORS, and Body-Parser—are fundamental for setting up a Node.js server. Express provides the core framework for building server-side applications, CORS middleware enables secure cross-origin requests, and Body-Parser facilitates handling incoming request data. Together, they form a robust foundation for any web application built on Node.js.