Aben
Aben

Reputation: 21

Facing "401 Unauthorized" Issue

I'm encountering a "401 Unauthorized" error when trying to make a request to my backend API using Axios in my React application. I've implemented user authentication and stored the JWT token in local storage after the user logs in.

I'm trying to send an authenticated request to my backend API to create a new store using a multipart/form-data POST request. I'm setting the Authorization header in Axios with the JWT token stored in local storage, but I keep getting a "401 Unauthorized" response.

Can someone please help me understand why I'm still getting a "401 Unauthorized" error even though I'm sending the token in the Authorization header? Is there something I'm missing in my implementation or configuration?

const submitAddStore = async (event) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append("pic", pic);
    formData.append("title", title);
    formData.append("tele", tele);
    formData.append("desc", desc);
    formData.append("location", location);

    try {
      if (!title || !tele || !desc || !pic || !location) {
        Swal.fire({
          position: "center",
          icon: "warning",
          title: "عذرا",
          text: "المرجو ملء جميع الحقول   ",
        });
        return;
      }
      const token = localStorage.getItem("token"); // Get the authentication token from local storage

      const result = await axios.post(
        "http://localhost:5000/api/create-store",
        formData,
        {
          headers: {
            "content-type": "multipart/form-data",
            Authorization: `Bearer ${token}`,
          },
        }
      );

the backend code:

app.post(
  "/api/create-store",
  protect,
  upload2.single("pic"),
  async (req, res) => {
    const { title, desc, tele, location } = req.body;
    const picName = req.file.filename;

    try {
      const newStore = new store({
        title,
        desc,
        tele,
        location,
        pic: picName,
        owner: req.user._id,
      });
      await newStore.save();
      res.json({ status: "ok" });
    } catch (error) {
      console.error("Error creating store:", error);
      res.json({ status: "error" });
    }
  }
);

and the MIddleware that I've use:

import jwt from "jsonwebtoken";
import asyncHandler from "express-async-handler";
import User from "../models/useModel.js";

const protect = asyncHandler(async (req, res, next) => {
  let token;

  token = req.cookies.jwt;

  if (token) {
    console.log("Received Token:", token);

    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      console.log("Decoded User ID:", decoded.userId);

      req.user = await User.findById(decoded.userId).select("-password");
      console.log("User from Database:", req.user);

      next();
    } catch (error) {
      console.error(error);
      res.status(401);
      throw new Error("Not authorized, token failed");
    }
  } else {
    res.status(401);
    throw new Error("Not authorized, no token");
  }
});

export default protect;

Upvotes: 1

Views: 301

Answers (1)

Jay Patel
Jay Patel

Reputation: 306

Change your middleware file as below:

import jwt from "jsonwebtoken";
import asyncHandler from "express-async-handler";
import User from "../models/useModel.js";

const protect = asyncHandler(async (req, res, next) => {
  let token;

  //token = req.cookies.jwt;
    token = req.headers['Authorization'].split(' ')[1];

  if (token) {
    console.log("Received Token:", token);

    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      console.log("Decoded User ID:", decoded.userId);

      req.user = await User.findById(decoded.userId).select("-password");
      console.log("User from Database:", req.user);

      next();
    } catch (error) {
      console.error(error);
      res.status(401);
      throw new Error("Not authorized, token failed");
    }
  } else {
    res.status(401);
    throw new Error("Not authorized, no token");
  }
});

export default protect;

Upvotes: 0

Related Questions