Here’s a guide for Day 1 of your Node.js learning journey, covering the installation and basics of Express, setting up an MVC architecture, installing and configuring Nodemon, and using Postman for testing basic `GET` and `POST` operations.
1. Install Node.js
Before starting, ensure you have Node.js installed on your machine. If not, download and install it from [Node.js official website](https://nodejs.org/).
---
2. Express Installation
1. Create a new project directory:
mkdir my-express-app
cd my-express-app
2. Initialize a new Node.js project:
npm init -y
3. Install Express:
npm install express
---
3. MVC Architecture Concept
MVC stands for Model-View-Controller. It’s a design pattern used to separate the concerns of your application:
- Model: Manages the data and business logic.
- View: Handles what the user sees (UI).
- Controller: Receives input from the user and makes calls to Model and View to perform appropriate actions.
Express MVC Setup:
- Models: Will contain the data structure or schema.
- Views: Will manage what users see (usually in web applications).
- Controllers: Will handle the logic of your application.
---
4. Nodemon Installation
Nodemon is a tool that automatically restarts your Node.js server when file changes in the directory are detected.
1. Install Nodemon globally:
npm install -g nodemon
2. Alternatively, install Nodemon as a development dependency:
npm install nodemon --save-dev
3. Update your `package.json` to use Nodemon:
json:
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
Now, you can run your app in development mode with:
npm run dev
---
5. Express Server Configuration
1. Create a new `index.js` file:
const express = require('express');
const app = express();
// Middleware to parse JSON
app.use(express.json());
// Basic route
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
2. Start your server:
npm run dev
Your Express server should be running on `http://localhost:3000`.
---
6. Postman Installation
1. Download and install Postman from [Postman official website](https://www.postman.com/downloads/).
2. Launch Postman after installation.
---
7. Basic `GET` and `POST` Operations in API
1. `GET` Operation:
- Add the following route to `index.js`:
app.get('/api/greet', (req, res) => {
res.json({ message: 'Hello from the API!' });
});
- Test with Postman:
- Open Postman.
- Set the request type to `GET`.
- Enter the URL `http://localhost:3000/api/greet`.
- Click Send.
- You should see a response `{ "message": "Hello from the API!" }`.
2. `POST` Operation:
- Add the following route to `index.js`:
app.post('/api/echo', (req, res) => {
const { message } = req.body;
res.json({ echo: message });
});
- Test with Postman:
- Open Postman.
- Set the request type to `POST`.
- Enter the URL `http://localhost:3000/api/echo`.
- Go to the Body tab and select raw and then JSON format.
- Enter the following JSON:
{
"message": "Hello Express"
}
- Click Send.
- You should see a response `{ "echo": "Hello Express" }`.
---
Summary
- Express Installation: Learned how to install and configure Express.
- MVC Architecture: Understood the MVC pattern in the context of Express.
- Nodemon Installation: Installed Nodemon to automatically restart the server on changes.
- Express Server Configuration: Set up a basic Express server.
- Postman Installation: Installed Postman for API testing.
- Basic API Operations: Implemented and tested basic `GET` and `POST` operations using Postman.
--------------------------------------------------------------------------------------------------------------------
server.js
const express=require('express'); //object create const app=express(); const port=4000; //configuration code for accepting json data / form data from ui app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.get('/',(req,res)=>{ res.send("<h3>Welcome to my Express Application and Coding and be Happy</h3>"); }) app.get('/test1',(req,res)=>{ res.send("<ul><li>hello kolkata</li><li>hello pune</li></ul>"); }) app.get('/test2',(req,res)=>{ let emp={id:10,nm:'raj',age:33,city:['pune','goa','punjab']}; res.json(emp); }) app.post('/insert',(req,res)=>{ let data=req.body; console.log(data); res.status(200).json({msg:"thank you data received"}); }) app.post('/login',(req,res)=>{ let data=req.body; if(data.uid=="sourav07" && data.pwd=="1234") { res.status(200).json({msg:"user is valid"}); } else { res.status(200).json({msg:"user is invalid"}); } }) app.get('/edit/:uid',(req,res)=>{ let id=req.params.uid; console.log("Required id :"+id); res.status(200).json({msg:"id received"}); }) app.listen(port,()=>{ console.log(`server is running in the port ${port}`); })
package.json
{ "name": "satsunapp", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev":"nodemon server.js" }, "author": "s.kundu", "license": "ISC", "dependencies": { "express": "^4.19.2", "nodemon": "^3.1.4" } }
Comments
Post a Comment