Home > front end >  React axios.get 401 unauthorized
React axios.get 401 unauthorized

Time:10-03

I used the postman for testing my url,and it has response data(It's correct). Url:http://localhost:8000/api/products/find/6337d5d73ec2c05d7c11bc63(ProductId). In postman,it could get response data. I wonder I do give it Bearer token in my requestMethods.js,which imported in /pages/Product.jsx.

But when I use the same id in axios.get,it said error: Error:GET http://localhost:8000/api/products/find/6337d5d73ec2c05d7c11bc63 401 (Unauthorized) enter image description here

can someone just help me solve this question? In /pages/product.jsx line 145,157 are got tag in the photo.

Here are my relative Codes:

requestMethods.js

import axios from "axios";

const BASE_URL = "http://localhost:8000/api/"
const TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9......"

export const publicRequest = axios.create({
    baseURL: BASE_URL,
});

export const userRequest = axios.create({
    baseURL: BASE_URL,
    headers: { token: `Bearer ${TOKEN}` },
});

/pages/Product.jsx It's mainly codes of website.

import { useLocation } from 'react-router-dom'
import { useState, useEffect } from 'react';
import { publicRequest,userRequest } from './requestMethods';

const Product = () => {
    // 回傳路徑
    const location = useLocation();
    const id = location.pathname.split("/")[2];
    const [product, setProduct] = useState({});
    useEffect(() => {
        const getProduct = async () => {
            try {
                const res = await publicRequest.get("/products/find/"   id);//HERE USE REQUESTMETHODS.JS and it's it sad line:145
                console.log(res.data)
                setProduct(res.data);
            }
            catch { } }
        getProduct();//line 157
    }, [id])
    
}

export default Product

index.js

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRouter = require("./routes/user");
const authRouter = require("./routes/auth");
const productRouter = require("./routes/product");

const cors=require("cors");
dotenv.config();
mongoose.connect(
    process.env.MONGO_URL)
    .then(() => console.log("connect"))
    .catch(((err) => {
        console.log(err);
    }));

app.use(express.json());
app.use(cors());
app.use("/api/users", userRouter);
app.use("/api/auth", authRouter);
app.use("/api/products", productRouter);//USE THE ROUTES/PRODUCT.JS
app.use("/api/orders", orderRouter);
app.use("/api/cart", cartRouter);
app.use("/api/checkout",stripeRouter)
app.listen(process.env.PORT || 8000, () => {
    console.log("Run server")
})

routes/product.js

router.put("/:id", verifyTokenAndAdmin, async (req, res) => {

    try {
        const updatedProduct = await Products.findByIdAndUpdate(req.params.id, {
            $set: req.body
        }, { new: true }
        );
        res.status(200).json(updatedProduct);
    } catch (err) {
        res.status(500).json(err);
    }

});


//delete
router.delete("/:id", verifyTokenAndAdmin, async (req, res) => {
    try {
        await Products.findByIdAndDelete(req.params.id);
        res.status(200).json("Products has been deleted.")
    } catch (err) {
        res.status(500).json(err);
    }
})
//get  product
router.get("/find/:id", verifyTokenAndAdmin, async (req, res) => {
    try {
        const product = await Products.findById(req.params.id);
        res.status(200).json(product);

    } catch (err) {
        res.status(500).json(err);
    }
})

verifyToken.js

const jwt = require("jsonwebtoken");

const verifyToken = (req, res, next) => {
    const authHeader = req.headers.token;

    if (authHeader) {
        const token = authHeader.split(" ")[1];
        jwt.verify(token, process.env.JWT_SEC, (err, user) => {

            if (err) 
                res.status(401).json("Token is not valid!")
            req.user = user;
            next();
        })
    }
    else {
        return res.status(401).json("You are not authentication!" );
    }
}


module.exports = { verifyToken, verifyTokenAndAuth, verifyTokenAndAdmin };

CodePudding user response:

The reason is you are using publicRequest axios function which does not include bearer token header. Use userRequest function.

Try using the code below in your axios request from frontend:

const res = await userRequest.get("/products/find/${id}");

Instead of double quotes use string literal. Stack overflow is using my string literal as code snippet that's why I wrote in double quotes.

Also remove the extra slash after api from BASE_URL like this:

const BASE_URL = "http://localhost:8000/api"

Also check in your verifyToken.js file if you have written the functions verifyTokenAndAuth and verifyTokenAndAdmin which you are exporting. If not then please write those functions in verifyToken.js file and then export because you are using verifyTokenAndAdmin middleware in your api. Also please check that server is running and not crashing before making a request.

  • Related