RAGISTER API

Project
  1. Create a MongoDB schema for storing user information. This schema should include fields such as name, email, password, and any other relevant information you want to collect from users during registration.
  2. Set up an Express server with routes for handling registration requests. You can use the Express Router module to define routes for handling POST requests to your registration endpoint.
  3. In your registration route handler, use the Mongoose library to create a new user document based on the data submitted in the registration request. You’ll want to hash the password using a library like bcrypt before storing it in the database.
  4. Once the user has been successfully registered, you can generate a JSON Web Token (JWT) to include in the response to the client. This token can be used to authenticate the user for subsequent requests.
  5. In your React client, you’ll need to create a registration form that sends a POST request to your registration API endpoint when the user submits the form. You can use a library like Axios or the built-in Fetch API to send the request.
  6. Once the registration request is successful, you can store the JWT in local storage or a cookie to use for subsequent authenticated requests.

EXAMPLE : RAGISTER API

First, create a User model using Mongoose to define the schema for storing user information:

const mongoose = require(‘mongoose’);

const bcrypt = require(‘bcrypt’);

const jwt = require(‘jsonwebtoken’);

const userSchema = new mongoose.Schema({

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

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

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

    tokens:[

{

            token:{type:String,required:true}

        }]

})

userSchema.methods.generateAuthToken = async function (){

    try {

        console.log(this._id);

        const token = jwt.sign({_id:this._id.toString()}, process.env.SECRET_KEY);

        this.tokens = this.tokens.concat({token:token})

        await this.save();

        return token;

    } catch (error) {

        console.log(error);

    }};

userSchema.pre(“save”, async function(next){

    if(this.isModified(“password”)){

            this.password = await bcrypt.hash(this.password,12);

    }

    next();

});

const User = mongoose.model(“user”,userSchema);

module.exports = User;

This model defines the User schema with fields for name, email, and password. The pre('save') middleware function uses bcrypt to hash the user’s password before saving it to the database.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Next, create an Express route for handling registration requests:

const User = require(“../model/userSchema”);

const register = async(req,res) =>{

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

    if( !name || !email || ! password){

      return res.status(422).json({error:”please filled the field properly”});

    }

    try {

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

      if(userExist){

        return res.status(422).json({erroe:”email already exist”});

      }

      else{

        const user = new User({name, email,password});

      await user.save();

      res.status(201).json({message:”user ragistered successfully”});

      }

    } catch (error) {

      console.log(error);

      }

};

module.exports  = {register};

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

This route handles POST requests to the /register endpoint. It extracts the name, email, and password fields from the request body and creates a new User document using the Mongoose model.

var express = require(‘express’);

var router = express.Router();

var {register}= require(“../controller/userdata.js”);

/* GET home page. */

router.route(“/register”).post(register);

module.exports = router;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

This React component creates a registration form with fields for name, email, and password. When the user submits the form, it sends a POST request to the /api/register endpoint using the axios.

WHAT IS CRUD API

LOGIN API

Leave a Comment