Routing concept in Express , Controller Concept in Express , Get() , Post() routing in express , Testing in postman. Mongoose (ODM) install , Connectivity with Mongodb using mongoose.Connect() . Examples
Routing concept in Express , Controller Concept in Express , Get() , Post() routing in express , Testing in postman. Mongoose (ODM) install , Connectivity with Mongodb using mongoose.Connect() . Examples
1. Routing Concept in Express
- Routing refers to how an application responds to client requests for a specific endpoint (URL) with a specific HTTP method (GET, POST, etc.).
- Basic Routing Example:
```javascript
const express = require('express');
const app = express();
// GET route
app.get('/home', (req, res) => {
res.send('Welcome to the Home Page!');
});
// POST route
app.post('/submit', (req, res) => {
res.send('Form Submitted!');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
```
- In the example above, when the user visits `/home` with a GET request, they'll see "Welcome to the Home Page!". Similarly, a POST request to `/submit` triggers the message "Form Submitted!".
2. Controller Concept in Express
- Controllers are responsible for handling the request logic. They separate the request-handling logic from the routing layer.
- Example of Controller Setup:
- Create a file named `userController.js`:
```javascript
exports.getUser = (req, res) => {
res.json({ message: 'GET user data' });
};
exports.createUser = (req, res) => {
const userData = req.body;
res.json({ message: 'User created', userData });
};
```
- In your main `app.js` file:
```javascript
const express = require('express');
const { getUser, createUser } = require('./userController');
const app = express();
app.use(express.json());
app.get('/user', getUser);
app.post('/user', createUser);
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
```
3. GET() and POST() Routing in Express
- GET Request:
- Typically used to retrieve data from the server.
- Example:
```javascript
app.get('/products', (req, res) => {
res.json({ message: 'Here are the products' });
});
```
- POST Request:
- Typically used to send data to the server.
- Example:
```javascript
app.post('/products', (req, res) => {
const newProduct = req.body;
res.json({ message: 'Product added', newProduct });
});
```
4. Testing in Postman
- GET Request:
- Set method to `GET`.
- Enter URL, e.g., `http://localhost:3000/products`.
- Click `Send`.
- POST Request:
- Set method to `POST`.
- Enter URL, e.g., `http://localhost:3000/products`.
- Go to the `Body` tab, select `raw`, and choose `JSON`.
- Enter JSON data, e.g., `{ "name": "Laptop", "price": 1000 }`.
- Click `Send`.
5. Mongoose (ODM) Installation
- Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.
- Install Mongoose:
```bash
npm install mongoose --save
```
6. Connectivity with MongoDB using `mongoose.connect()`
- Connect to MongoDB:
```javascript
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Connected to MongoDB');
})
.catch(err => {
console.error('Error connecting to MongoDB', err);
});
```
- Example Schema and Model:
```javascript
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
email: String,
password: String
});
const User = mongoose.model('User', userSchema);
// Example of saving a new user
const newUser = new User({
name: 'John Doe',
email: 'john.doe@example.com',
password: 'securepassword'
});
newUser.save()
.then(() => console.log('User saved!'))
.catch(err => console.error('Error saving user', err));
```
This guide should help you set up routing and controllers in Express, test them using Postman, and connect your application to MongoDB using Mongoose.
--------------------------------------------------------------------------------------------------------------------------
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", "mongoose": "^8.5.2", "nodemon": "^3.1.4" } }
server.js
const express=require('express'); const testroute=require('./routes/testroute'); const mongoose=require('./database/dbconnect'); //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 })); //register route app.use('/api',testroute); app.listen(port,()=>{ console.log(`server is running in the port ${port}`); })testroute.jsconst express=require('express'); const TC=require('../controllers/TestController'); const SC=require('../controllers/ShowController'); const route=express.Router(); route.get('/test1',(req,res)=>{ res.send(`<h3>Route is working fine</h3>`); }) route.get('/all',SC); route.post('/adduser',TC.insertuser); route.get('/test2',TC.display); module.exports=route;showController.jsconst ShowController=(req,res)=>{ let r={id:10,nm:'sourav',age:37,dept:'computer',skills:['c','c++','php','java']}; res.status(200).json(r); } module.exports=ShowController;testController.jsclass TestController { static display=(req,res)=>{ res.status(200).json({id:25,nm:'raj',age:22}); } static insertuser=(req,res)=>{ let r=req.body; console.log(r); res.status(200).json({msg:'insert is success'}); } } module.exports=TestController;dbconnect.jsconst mongoose = require('mongoose'); const main=async()=>{ await mongoose.connect('mongodb://127.0.0.1:27017/merndb'); } main().then( ()=>{ console.log("mongodb connected success..!")} ).catch( (err)=>{ console.log(err)} ) module.exports=mongoose;
Comments
Post a Comment