We'll use express to configure the routes. This can be done using http , but it'll be easier with express.
1. install express
npm i express
2. Create route file. Example homeRoute.js here.
const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.send('Home Page'); }); module.exports = router;
express.Router() is a feature in Express.js that allows you to create modular, mountable route handlers. A Router instance is essentially a mini-express application, capable only of performing middleware and routing functions. It doesn't function on its own but is intended to be used as part of a larger app.
3. Set up the server.
const express = require('express'); const app = express(); const port = 3000; // Import routes const homeRoute = require('./routes/homeRoutes.js'); // Use routes app.use('/', homeRoute); // Start the server app.listen(port, () => { console.log(`Server running at http://127.0.0.1:${port}/`); });
4.
Run the server
node server.js
or create a new script.
In package.json , create a script = "server":"node server.js";
npm run server
1.Use Spring Initializr https://start.spring.io/ to generate a new Spring Boot project.
Project: Maven Project
Language: Java
Spring Boot: (select the latest stable version)
Project Metadata -
Group (com.example),
Artifact(backend),
Name(backend),
Description(Demo project for Spring Boot),
Package Name(com.example.backend)
Dependencies: Spring Web
Download the generated project and extract it to your desired directory.
Generated project will have a structure like this-
backend/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/example/backend/ │ │ │ ├── BackendApplication.java │ │ │ └── controllers/ │ │ │ ├── HomeController.java │ │ └── resources/ │ │ ├── application.properties │ └── test/ │ └── java/ │ └── com/example/backend/ │ └── BackendApplicationTests.java └── pom.xml
2. Create HomeController.js in java/com/example/backend/controllers .
package com.example.backend.controllers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/home") public class HomeController{ @GetMapping public String home(){ return "Home Page"; } }
3. Update BackendApplication.java
package com.example.backend; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BackendApplication { public static void main(String[] args) { SpringApplication.run(BackendApplication.class, args); } }
4. Run the server using Maven. In windows cmd-
mvnw.cmd spring-boot:run
Separation Of Controllers and Routers in SpringBoot.
In Spring Boot, it's common practice to keep controllers (which handle the web requests) and service logic separate. However, unlike in Node.js where you might explicitly separate routes and controllers into different files, Spring Boot doesn't have a direct equivalent of "router" files. Instead, the routing is handled by the combination of the @RequestMapping annotations on your controllers.
Typical Spring Boot Project Structure: Controller Layer: Contains classes annotated with @RestController or @Controller. Handles HTTP requests and maps them to appropriate methods. Service Layer: Contains business logic. Typically consists of classes annotated with @Service. Repository Layer: Handles data access. Typically consists of interfaces annotated with @Repository. Model Layer: Contains data models. Typically consists of classes annotated with @Entity or other data-related annotations.
my_springboot_project/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/example/backend/ │ │ │ ├── controllers/ │ │ │ │ ├── HomeController.java │ │ │ │ ├── AboutController.java │ │ │ │ └── ContactController.java │ │ │ ├── services/ │ │ │ │ └── HomeService.java │ │ │ ├── repositories/ │ │ │ │ └── HomeRepository.java │ │ │ └── models/ │ │ │ └── HomeModel.java │ │ └── resources/ │ │ ├── application.properties │ └── test/ │ └── java/ │ └── com/example/backend/ │ └── BackendApplicationTests.java └── pom.xml
In Node.js, using Express, you typically create routes and controllers separately, though sometimes they are combined for simplicity. Here's an example:
1. Router File
const express = require('express'); const router = express.Router(); const homeController = require('../controllers/homeController'); router.get('/', homeController.home); router.get('/about', homeController.about); module.exports = router;
2. Controller File
exports.home = (req, res) => { res.send('Home Page'); };
3. Main Application File
const express = require('express'); const app = express(); const homeRoutes = require('./routes/home'); app.use('/home', homeRoutes); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
1. Structure and Modularity
Controllers and routes are usually kept in separate files.
Routing is done in route files using router objects.
Controller functions are simple JavaScript functions exported from modules.
2. Dependency Injection
Dependency injection is not built-in; you might use third-party libraries like inversify for this purpose.
Typically, dependencies are managed manually using require.
3. Annotations vs Configuration
Uses JavaScript code and functions to define routes and controllers.
More imperative style, where you explicitly define how routes should be handled.
4. Middleware
Middleware functions are used extensively to handle requests, authentication, logging, etc.
Defined and applied using app.use() or router.use().
In Spring Boot, you typically have a controller class that handles HTTP requests. The routing is often defined with annotations within the controller class itself.
Controller File
package com.example.backend.controllers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/home") public class HomeController { @GetMapping public String home() { return "Home Page"; } @GetMapping("/about") public String about() { return "About Page"; } }
Main Application File
package com.example.backend; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BackendApplication { public static void main(String[] args) { SpringApplication.run(BackendApplication.class, args); } }
1. Structure and Modularity
Controllers are classes annotated with @RestController.
Routes are defined using annotations such as @RequestMapping and @GetMapping directly in the controller class.
Spring Boot relies heavily on annotations for configuration and routing.
2. Dependency Injection
Built-in dependency injection framework.
Managed using annotations like @Autowired for injecting services, repositories, etc.
3. Annotations vs Configuration
Uses annotations to define routes and controllers.
Declarative style, where annotations handle most of the configuration automatically.
4. Middleware
Uses filters and interceptors to achieve similar functionality to middleware in Express.
Filters can be applied globally or to specific endpoints.
1. Configure the mongoose and setup database.
npm i mongoose
const mongoose=require('mongoose') const connectDB=async()=>{ try { await mongoose.connect("mongodb://localhost:27017/ecom-react"); console.log('MongoDb Connected') } catch (error) { console.error(err.message) process.exit(1) } } module.exports=connectDB
2. Setup Model File.
const mongoose=require('mongoose') const UserSchema = new mongoose.Schema({ name: { type: String, required: true, }, email: { type: String, required: true, unique: true, }, password: { type: String, required: true, }, address: { type: String, required: true, }, products: { type: mongoose.Schema.Types.ObjectId, ref: "Event", }, createdAt: { type: Date, }, }); const User=mongoose.model('User',UserSchema) module.exports=User
Role: Represents the data and the business logic of the application. Models are responsible for interacting with the database, defining the structure of the data, and providing methods to manipulate that data.
Key Points:
Defines schemas for the data.
Interacts with the database.
Contains methods for data validation, querying, and other data-related operations.
3. Setup Controller File.
const User = require("../models/UserModel"); exports.RegisterUser= async(req,res)=>{ const {name,email,password,address}=req.body; try{ let user=await User.findOne({email}); if(user){ return res.status(400).json({ msg: 'User already exists. Please login.' }); } user = new User({ name, email, password, address, createdAt:Date.now() }); await user.save(); res.send('User registered'); } catch (err) { console.error(err.message); res.status(500).send('Server error'); } }
Role: Contains the logic for handling HTTP requests and responses. Controllers handle the application’s behavior by interacting with models and sending responses back to the client. They perform actions such as creating, reading, updating, and deleting data.
Key Points:
Receives input from routes.
Calls model methods to interact with the database.
Processes data and prepares the response.
Sends the response back to the client.
4. Setup Routes File.
const express=require('express'); const { RegisterUser } = require('../controller/userController'); const router=express.Router(); router.get('/',(req,res)=>{ res.send('User Route page') }) router.post('/register',RegisterUser) module.exports=router;
Role: Defines the application’s routes and maps them to controller functions. Routes determine how the application responds to client requests for specific endpoints (URLs).
Key Points:
Defines HTTP endpoints (routes) and the HTTP methods (GET, POST, PUT, DELETE, etc.).
Maps each route to a corresponding controller function.
May include middleware to handle things like authentication, validation, etc.
5. Configure the server file.
const express = require("express"); const app = express(); const port = 3000; const connectDB = require("./database"); //Import Routes const userRoutes = require("./routes/UserRoutes"); //Connect DB connectDB(); //middleware to parse JSON app.use(express.json()); //use Routes app.use("/", userRoutes); //start the server app.listen(port, () => { console.log(`Server running on port ${port}`); });
1. Create Database using Mysql Command Line.
CREATE DATABASE ecom_angular;
SHOW DATABASES;
Configure Database Connection