Not Able to Fetch User Profile in JSON Format in my MERN Stack Project

Viewed 232

I am basically working on my MERN Stack Project , and in the backend node part , the issue where I am getting stuck from past few days is that , I am trying to access this protected route , http://localhost:3555/profile/me , and in order to access this protected route , I am sending along a token with it , but the thing is that when I am trying to do so on POSTMAN , I am not getting any response , and it constantly keeps displaying me , sending request only.

I believe that my code is correct , but still i don't know why it is getting stuck and I am not able to get a response back.

enter image description here

and , here is the code where I am trying to fetch the User Profile in JSON Format :

const express = require("express");
const router = express.Router();
const auth = require("../../middleware/auth");
const Profile = require("../../models/Profile");
const User = require("../../models/User");

//@route GET api/profile/me (Only Fetching My Profile , not all the profiles)
//@desc Get Current User's Profile
//@access Private;

router.get("/me", auth, async (req, res) => {
  try {
    const profile = await Profile.findOne({
      user: req.user.id,
    }).populate("user", ["name", "avatar"]);

    if (!profile) {
      return res.status(400).json({ msg: "there is no profile for this user" });
    }

    res.json(profile);
  } catch (err) {
    console.error(err.message);
    res.status(500).send("Server Error");
  }
});

module.exports = router;



Here is the Code for my Auth Middleware :

const jwt = require("jsonwebtoken");
const config = require("config");

//Our Middlware Function
module.exports = function (req, res, next) {
  //Get the Token From the Header :
  const token = req.header("x-auth-header");

  //Check if no token , available for the Protected Route  :
  if (!token) {
    return res.status(401).json({ msg: "No Token , Authorization Denied" });

    //Verifying the Token :
    try {
      const decoded = jwt.verify(token, config.get("jwtSecret"));
      req.user = decoded.user;
      next();
    } catch (err) {
      //TODO : To be Executed , in case if the token is not valid :
      res.status(401).json({ msg: "Token is not valid" });
    }
  }
};


1 Answers

I think you are missing a closing brace in the middleware:

if (!token) {
  return res.status(401).json({ msg: "No Token , Authorization Denied" });
}
// Verifying the Token :
try {
  const decoded = jwt.verify(token, config.get("jwtSecret"));
  req.user = decoded.user;
  next();
} catch (err) {
  //TODO : To be Executed , in case if the token is not valid :
  res.status(401).json({ msg: "Token is not valid" });
}
Related