Before starting, we need Node to be Installed on our machine.
For Window Click Here
For Mac Click Here
Create a new directory for your Express.js application. You can name it anything you like; for example, first-express-app.
Navigate to the Newly created Directory, Initialize a new Node.js application by running the following command. This will create a package.json file where your project dependencies will be stored.
cd first-express-app npm init -y
npm install -g express
The above command install an `express` package in the node_module directory and creates a directory named `express` inside the node_module folder in the root directory of your current folder. Additionally, it updates the package.json file with the Express dependency.
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000;
process.env.PORT: PORT Variable initialize in Environment variable file. if the `PORT` variable is not found in `env` file then use `3000` as a default port
app.get('/', (req, res) => { res.send('Hello World!'); }); app.post('/add-user', (req, res) => { console.log(req.body) res.send('User Data Recieve'); });
app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.post('/add-user', (req, res) => { console.log(req.body) res.send('User Data Recieve'); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
node server.js
Copy above code and save in file named server.js and Run the above code through below mentioned command.
// Output in Console ---> Server is running on http://localhost:3000 // Output in Browser ---> Hello World!
After following above listed steps, you'll have Express.js installed in your project, and you can start building your web application using this powerful framework. You can create a new Javascript file (e.g., server.js) and start writing your Express application code by requiring the Express module and initializing your Express application.