Project Setup
You must have Node.js and npm (the Node.js package manager) installed on your computer.
Once you have these installed, you can navigate to the directory where you want to create your project and initialize a Node.js project. To initialize a Node.js project, write npm init -y
in the terminal or command prompt. The -y
flag automatically answers “yes” to all of the questions that are asked during the initialization process, so the project is created with the default settings.
Once you have these installed, you can use the following steps to install Express:
-
Open a terminal or command prompt and navigate to the directory where you want to create your project.
-
Run the following command to initialize a new Node.js project:
cd learn-express
npm init -y
This will create a new Node.js project in the learn-express
directory. The package.json
file will be created with the default settings, and you can then start installing dependencies and building your project.
- Run the following command to install the Express library:
npm install express --save
Express library will be add it to your project as a dependency.
Optionaly you also install nodemon to automatically restarts the Node.js server whenever code changes are made. This is useful because it saves developers from having to manually stop and restart the server each time they make a change to their code. But if you have nodejs version 18.11.0 that comes with a watch mode you dont need nodemon
Run the following command to install nodemon:
npm i nodemon --save-dev
Nodemon library will be add it to your project as a devDependency.
- Create script
dev
inpackage.json
file
Add an entry to the scripts
section. The scripts
section of the package.json
file is used to define command-line scripts that can be run with the npm run
command.
Here’s an example of how you add a dev
script to the package.json
file with nodemon:
{
"name": "learn-express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}
Here’s an example of how you add a dev
script to the package.json
file using nodejs 18.11.0 --watch
flag:
{
"name": "learn-express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node --watch index.js",
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
This would start the server by running the index.js
file with the node
command. You can then run the dev script by using the npm run
command:
npm run dev
Server Setup
Create index.js file and then at the top of your index.js files:
const express = require("express");
For example, you might use the following code to create a basic Express server that listens for incoming HTTP requests on port 3000:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello, world!");
});
app.listen(3000, () => {
console.log("Server listening on port 3000");
});
You can then run your server by using the dev
command
npm run dev
Server will start the server and listen for incoming requests on port 3000. You can test your server by opening a web browser and navigating to http://localhost:3000
. You should see the message “Hello, world!” on the page.
Create Post request
To create a POST route with Express.js, you can use the app.post()
method, which is part of the Express.js routing API. This method takes two arguments: the path of the route, and a callback function that will be called when a request is received at that route.
Here’s an example of how you might create a POST route with Express.js:
app.post('/users', (req, res) => {
// Read the data from the request body
const data = req.body;
// Process the data (e.g. save to a database)
// Send a response to the client
res.send('Data received'); });
}
The app.post()
method is used to create a route at the /users
path. When a POST request is received at this route, the callback function is called and the request body is read from the req
object. The data can then be processed as needed, and a response can be sent to the client using the res
object.
To test this route, you can use a tool like Curl to send a POST request to the route. For example:
curl -X POST -d '{"name": "John Doe", "email": "john.doe@example.com"}' http://localhost:3000/users
This will send a POST request to the /users
route with the specified JSON data in the request body. The server will receive the request and call the callback function, which will process the data and send a response to the client.
Mac, Linux and Windows 10 already contains Curl, but for Windows 7 and 8, you still need to download and install Curl from the official website. curl for Windows
Dynamic value
To capture dynamic values in a URL with Express.js, you can use route parameters. Route parameters are named placeholders in the route path that are used to capture the values of dynamic segments in the URL.
Get request with dynamic values in a URL with Express.js:
app.get("/users/:id", (req, res) => {
// Read the value of the "id" parameter from the request
const id = req.params.id;
// Send the user data as a response to the client
res.send(`Data user id ${id}}`);
});
The app.get()
method is used to create a route at the /users/:id
path. This path contains a route parameter named id
, which is indicated by the :id
syntax. When a request is received at this route, the value of the id
parameter will be available in the req.params
object.
To test this route, you can use a tool like curl to send a GET request to the route with a URL that includes the value of the id
parameter. For example:
curl http://localhost:3000/users/123
This will send a GET request to the /users/123
route, and the server will call the callback function with the id
parameter set to 123
.
Post request with dynamic values in a URL with Express.js:
app.post("/users/:id", (req, res) => {
// Read the value of the "id" parameter from the request
const id = req.params.id; // Read the data from the request body
const data = req.body; // Process the data (e.g. save to a database) // Send a response to the client
res.send("Data received");
});
The app.post()
method is used to create a route at the /users/:id
path. This path contains a route parameter named id
, which is indicated by the :id
syntax. When a request is received at this route, the value of the id
parameter will be available in the req.params
object.
To test this route, you will need to use middleware to parse JSON, as Express does not parse JSON in the body by default. Then, you can use a tool like curl to send a POST request to the route with a URL that includes the value of the id
parameter. However, you should keep in mind that some additional steps may be required, depending on the specifics of your situation.
Here’s an example of how you to use express json middleware, at the top of your index.js files after app decalaration
const app = express();
app.use(express.json());
To send a POST request to the route.
curl -X POST -d '{"name": "John Doe", "email": "john.doe@example.com"}' http://localhost:3000/users/321
This will send a POST request to the /users/321
route with the specified JSON data in the request body. The server will receive the request and call the callback function, which will process the data and send a response to the client.