Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to Fetch User Orders – Getting 401 (Unauthorized) Error

I am currently working on a React application where users can view their orders. I have implemented user authentication using JSON Web Tokens (JWT). However, when attempting to fetch the user’s orders, I am consistently getting a 401 (Unauthorized) error.

React components

// UserOrders.jsx

import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { format } from 'date-fns';
import Cookies from 'js-cookie';

function UserOrders() {
  const [order, setOrder] = useState([]);

  useEffect(() => {
    const fetchOrder = async () => {
      try {
        const token = Cookies.get('token');
        if (!token) {
          console.error('No token found');
          return;
        }

        const response = await fetch('http://localhost:4000/api/v1/orders/me', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
          },
        });

        if (response.ok) {
          const data = await response.json();
          console.log(data.order);
          setOrder(data.order);
        } else {
          console.error('Failed to fetch user orders');
        }
      } catch (error) {
        console.error('Error fetching user orders', error);
      }
    };

    fetchOrder();
  }, []);

  // ... rest of the component
}

export default UserOrders;

server side

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// server.js

const orderRouter = require('express').Router();
const jwt = require('jsonwebtoken');

orderRouter.get("/me", isAuthenticated, async (req, res) => {
  const token = req.cookies.token;

  try {
    if (!token) {
      return res.status(401).send("Unauthorized: No token found");
    }

    const decodedToken = jwt.verify(token, 'your-secret-key');
    const userId = decodedToken.userId;

    const order = await Orders.find({ user: userId });
    res.json({ order });
  } catch (error) {
    res.status(401).send("Unauthorized: Invalid token");
  }
});

1.Check Token Existence
2.I’ve ensured that the token is being sent correctly in the Authorization header
3.On the server side, I’m decoding and verifying the token.

>Solution :

You’re sending the token as an Authorization header:

headers: {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${token}`,
}

But looking for it in the cookies:

const token = req.cookies.token;

Get it from the headers instead:

const token = req.headers.authorization;

(You may need to filter out the "Bearer " part of the value before validating the token, your debugging can confirm.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading