Courses/ Nodejs

Nodejs Tutorial

Node.js is a popular open-source, cross-platform JavaScript runtime environment that allows you to execute JavaScript code on the server-side. It's built on the Chrome V8 JavaScript engine and is designed for building scalable network applications and web services. Here are some key points about Node.js:

How NodeJS work?

A client send a request to server after some process server response to client.

How to create a package.json file

npm init

It only covers the most common items, and tries to guess sensible defaults.

How to install package in NodeJS

> npm install

Use `npm install ` afterwards to install a package

 and save it as a dependency in the package.json file.

Example1- npm install express

Example2- npm install -g nodemon

run nodemon- nodemon app.js

What is package?

Package is a inbuild code that was already written by JavaScript.

Example- Express

 

What is package.js?

It is the manifest file of any Node. js project and contains the metadata/information of the project.

What is dev dependencies?

keep information about package version and name under the dependencies key in package.json

 

What is module. Exports object

We can export functions, objects, and their references from one file and can use them in other files by importing them by require() method.

Example- secondfile.json

    studentdata = {

    name:"AKHILESH KUMAR",

   email:"akah.1223@gmail.com",

    mobile:9553796441

}

module.exports = studentdata;

firstfile.json

const student = require('./second');

console.log("hello", student);

output- hello {

  name: 'AKHILESH KUMAR',

  email: 'akah.1223@gmail.com',

  mobile: 9553796441

}

 

What is socket.io?

It is a web socket connection, by using this we can make server connection(bi directional) that cannot close the server connection.

 

What is module wrapper function in NodeJS

  • provides a level of abstraction that prevents variables and functions defined in one module from interfering with variables and functions defined in another module. This helps to keep the code organized and maintainable.
  • This is automatically done by NodeJS

 

Example-

(function (exports, require, module, __filename, __dirname) {  //module code });

 

Q10. How to send Api message in Json format

json() function sends a JSON response

Example-

res.json({ message: "Hello" });

Q11. How to set Status code in response

The res.status() function sets the HTTP status for the response

Example-

res.status(200).send("User Page");

Q12. How Creating New project

First Need to creating the necessary routes,

For handling login, registration, OTP generation and verification, and interacting with a database.

Step1. Setup Your Project

First, set up a new Node.js project and install the necessary packages.

mkdir node-otp-project

cd node-otp-project

npm init -y

npm install express body-parser mongoose bcryptjs jsonwebtoken nodemailer dotenv

 

express for building the server.

body-parser to parse incoming request bodies.

mongoose for MongoDB interaction.

bcryptjs for hashing passwords.

jsonwebtoken for creating and verifying JWTs.

nodemailer for sending OTP emails.

dotenv for managing environment variables.

 

Step2. Configure Your Environment

Create a .env file to store your environment variables:

PORT=5000

MONGO_URI=mongodb://localhost:27017/your_database

JWT_SECRET=your_jwt_secret

EMAIL_USER=your_email@example.com

EMAIL_PASS=your_email_password

 

 

Step3. Set Up the Server

Create a basic Express server in server.js:

const express = require('express');

const bodyParser = require('body-parser');

const mongoose = require('mongoose');

const authRoutes = require('./routes/auth');

 

require('dotenv').config();

 

const app = express();

app.use(bodyParser.json());

 

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })

  .then(() => console.log('MongoDB connected'))

  .catch(err => console.log(err));

 

app.use('/api/auth', authRoutes);

 

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

 

Step4. Create the User Model

Create models/User.js:

const mongoose = require('mongoose');

 

const userSchema = new mongoose.Schema({

  email: { type: String, required: true, unique: true },

  password: { type: String, required: true },

  otp: { type: String },

  otpExpires: { type: Date }

});

 

module.exports = mongoose.model('User', userSchema);

Step5. Set Up Authentication Routes

Create routes/auth.js:

 

const express = require('express');

const bcrypt = require('bcryptjs');

const jwt = require('jsonwebtoken');

const nodemailer = require('nodemailer');

const User = require('../models/User');

const router = express.Router();

 

const authenticateJWT = (req, res, next) => {

    const token = req.header('Authorization')?.replace('Bearer ', '');

    if (!token) return res.status(401).json({ message: 'Access denied' });

 

    jwt.verify(token, process.env.JWT_SECRET, (err, user) => {

      if (err) return res.status(403).json({ message: 'Invalid token' });

      req.user = user;

      next();

    });

  };

 

  // Example protected route

  router.get('/data', authenticateJWT, (req, res) => {

    res.status(200).json({ message: 'Protected data', user: req.user });

  });

const transporter = nodemailer.createTransport({

  service: 'gmail',

  auth: {

    user: process.env.EMAIL_USER,

    pass: process.env.EMAIL_PASS

  }

});

 

// Helper function to send OTP

const sendOTP = async (email, otp) => {

  const mailOptions = {

    from: process.env.EMAIL_USER,

    to: email,

    subject: 'Your OTP Code',

    text: `Your OTP code is ${otp}`

  };

  await transporter.sendMail(mailOptions);

};

 

// Registration

router.post('/register', async (req, res) => {

  const { email, password } = req.body;

  try {

    const hashedPassword = await bcrypt.hash(password, 10);

    const newUser = new User({ email, password: hashedPassword });

    await newUser.save();

    res.status(201).json({ message: 'User registered' });

  } catch (error) {

    res.status(500).json({ message: error.message });

  }

});

// Send OTP

router.post('/send-otp', async (req, res) => {

  const { email } = req.body;

  try {

    const user = await User.findOne({ email });

    if (!user) return res.status(404).json({ message: 'User not found' });

 

    const otp = Math.floor(100000 + Math.random() * 900000).toString();

    user.otp = otp;

    user.otpExpires = Date.now() + 15 * 60 * 1000; // 15 minutes

    await user.save();

 

    await sendOTP(email, otp);

    res.status(200).json({ message: 'OTP sent' });

  } catch (error) {

    res.status(500).json({ message: error.message });

  }

});

 

// Verify OTP and Login

router.post('/verify-otp', async (req, res) => {

  const { email, otp, password } = req.body;

  try {

    const user = await User.findOne({ email });

    if (!user) return res.status(404).json({ message: 'User not found' });

 

    if (user.otp !== otp || Date.now() > user.otpExpires) {

      return res.status(400).json({ message: 'Invalid or expired OTP' });

    }

 

    const isMatch = await bcrypt.compare(password, user.password);

    if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' });

 

    const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });

    user.otp = null;

    user.otpExpires = null;

    await user.save();

 

    res.status(200).json({ token });

  } catch (error) {

    res.status(500).json({ message: error.message });

  }

});

 

module.exports = router;

 

How to call register and login Api through postman

Set Up the Registration Request

  1. Select Method and URL
    • Choose POST as the request method.
    • Enter the URL for your registration endpoint. For example: http://localhost:5000/api/auth/register.
  2. Set Up the Request Body
    • Click on the Body tab.
    • Select raw and choose JSON from the dropdown menu.
    • Enter the registration details in JSON format. For example:

{

  "email": "user@example.com",

  "password": "yourpassword"

}

  1. Send the Request
  • Click on the Send button.
  • You should receive a response indicating that the user has been registered successfully, or an error message if something went wrong.

Student Feedback

4.2 /5
Average Ratings
  • ( 79% )
  • ( 30% )
  • ( 69% )
  • ( 29% )
  • ( 10% )

02 Reviews

  • Jassica Treat

    Pellentesque ultrices orci id justo vehicula, non aliquam erat lacinia Mam rem aperiam, eaque ipsa qua tore veritatis.

  • Willimes Doe

    Pellentesque ultrices orci id justo vehicula, non aliquam erat lacinia Mam rem aperiam, eaque ipsa qua tore veritatis.

Post Review