nodejsnotes

Topic 001: express, cors, body parser packages

Topic 001: express, cors, body parser packages

Express

Overview

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.

Key Features

Example Usage

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 (Cross-Origin Resource Sharing)

Overview

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.

Key Features

Example Usage

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");
});

Advanced Configuration

const corsOptions = {
  origin: "http://example.com",
  methods: "GET,POST",
  allowedHeaders: ["Content-Type", "Authorization"],
  credentials: true,
  optionsSuccessStatus: 204,
};

app.use(cors(corsOptions));

Body-Parser

Overview

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.

Key Features

Example Usage

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");
});

Advanced Configuration

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
  })
);

Conclusion

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.