skip to Main Content

Hi guys i am newbie in react js, i have a problem about getting data from server side and routing in reactjs, i am using axios and jsonwebtoken to get the data, but it’s not working,

i have check the inspect from browser and there’s no error in there, but my website is still not responding

maybe you can help me to fix this problem

thanks in advance

Here is my code from "AuthController.js"

import UserModel from "../Models/userModel.js";
import bcrypt from 'bcrypt'
import jwt from "jsonwebtoken";


// Registering a new User
export const registerUser = async (req, res) => {
  const { username, password, firstname, lastname } = req.body
  const salt = await bcrypt.genSalt(10)
  const hashedPass = await bcrypt.hash(password, salt)
  // req.body.passowrd = hashedPass

  const newUser = new UserModel({
    username,
    password: hashedPass,
    firstname,
    lastname
  })

  try {
    // check username
    const oldUser = await UserModel.findOne({ username })
    if (oldUser) {
      return res.status(400).json({ message: "The username is already exist" })
    }

    const user = await newUser.save()
    const token = jwt.sign({
      username: user.username, id: user._id
    }, process.env.JWT_KEY, { expiresIn: '1h' })

    res.status(200).json({ user, token })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
};


// login user 

export const loginUser = async (req, res) => {
  const { username, password } = req.body;

  try {
    const user = await UserModel.findOne({ username: username })

    if (user) {
      const validity = await bcrypt.compare(password, user.password);

      validity ? res.status(200).json(user) : res.status(400).json("Wrong Password")
      const token = jwt.sign(
        { username: user.username, id: user._id },
        process.env.JWTKEY,
        { expiresIn: "1h" }
      );
      res.status(200).json({ user, token });
    } else {
      res.status(404).json("User not found");
    }

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


here is my Auth Reducer

const authReducer = (state = { auhtData: null, loading: false, error: false }, action) => {
  switch (action.type) {
    case "AUTH_START": return { ...state, loading: true, error: false };
    case "AUTH_SUCCES":
      localStorage.setItem("profile", JSON.stringify({ ...action?.data }))
      return { ...state, authData: action.data, loading: false, error: false };
    case "AUTH_FAIL": return { ...state, loading: false, error: true }
    default: return state;
  }
}

export default authReducer

my Auth action

import * as AuthApi from '../api/AuthRequests.js';

export const logIn = (formData) => async (dispatch) => {
  dispatch({ type: "AUTH_START" });
  try {
    const { data } = await AuthApi.logIn(formData);
    dispatch({ type: "AUTH_SUCCESS", data: data });
  } catch (error) {
    console.log(error);
    dispatch({ type: "AUTH_FAIL" });
  }
};

export const signUp = (formData) => async (dispatch) => {

  dispatch({ type: "AUTH_START" })
  try {
    const { data } = await AuthApi.signUp(formData)
    dispatch({ type: "AUTH_SUCCES", data: data })

  } catch (error) {
    console.log(error)
    dispatch({ type: "AUTH_FAIL" })
  }
}

my Auth Request for API

import axios from 'axios'


const API = axios.create({ baseURL: "http://localhost:5000" });

export const logIn = (formData) => API.post('/auth/login', formData);

export const signUp = (formData) => API.post('/auth/register', formData);

here is my index.js

import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import dotenv from 'dotenv';
import cors from 'cors'
import AuthRoute from './Routes/AuthRoute.js'
import UserRoute from './Routes/UserRoute.js'
import PostRoute from './Routes/PostRoute.js'


//Routes
const app = express();


// Middleware
app.use(bodyParser.json({
  limit: '30mb', extended: true,
}))

app.use(bodyParser.urlencoded({
  limit: '30mb', extended: true,
}))

app.use(cors())

dotenv.config();


mongoose.connect(process.env.MONGO_DB, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => app.listen(process.env.PORT, () => console.log(`Listening to ${process.env.PORT}`)))
  .catch((error) => console.log(error));


// usage of routes
app.use('/auth', AuthRoute)
app.use('/user', UserRoute)
app.use('/post', PostRoute)

2

Answers


  1. It’s probably because of validity ? res.status(200).json(user) : res.status(400).json("Wrong Password"). You are sending a response multiple times.

    Try with:

    export const loginUser = async (req, res) => {
      const { username, password } = req.body;
    
      try {
        const user = await UserModel.findOne({ username: username })
    
        if (user) {
          const validity = await bcrypt.compare(password, user.password);
    
          if (!validity) return res.status(400).json("Wrong Password");
          
          const token = jwt.sign(
            { username: user.username, id: user._id },
            process.env.JWTKEY,
            { expiresIn: "1h" }
          );
          res.status(200).json({ user, token });
        } else {
          res.status(404).json("User not found");
        }
    
      } catch (error) {
        res.status(500).json({ message: error.message })
      }
    }
    
    Login or Signup to reply.
  2. var passport  = require("passport");
    var passportJWT = require('passport-jwt');
    var User = require("../models/user");
    var config = require('../config');
    var ExtractJwt = passportJWT.ExtractJwt;
    var Strategy = passportJWT.Strategy;
    
    var opts = {
        secretOrKey: config.secret,
        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
    }
    
    module.exports = function () {
    
        var strategy = new Strategy(opts, function(payload, done) {
            User.findById(payload.id, function(err, user) {
                if (user) {
                    return done(null, {id: user.id, payload: user});
                }else {
                    return done(new Error("User not found"), null);
                }
            });
        });
    
        passport.use(strategy);
        return {
            initialize: function() {
                return passport.initialize();
    
            },
            authenticate: function () {
                const a = passport.authenticate("jwt", {session: false});
                return a;
            }
        };
    };
    

    You can use Passport and middleware.
    Also it seems your process.env.JWTKEY is missing.
    So please check the value via console.log(process.env.JWTKEY)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search