skip to Main Content

Whenever I click the login button of my web page built with vite-react(frontend:5173), express(server 5000, to handle cookies httpOnly) and Django(backend:8080). the console logs an error of (GET http://localhost:5000/api/users/me 401 (Unauthorized)). Django terminal using VS Code also logs the same error. I’ve narrowed down the problem that it’s between the React and express server. I’m also using redux-toolkit for the project and here is a part of the reducer I’m using to handle getting the user

const getUser = createAsyncThunk(
    'users/me',
    async (_, thunkAPI) => {
    try{
            //const accessToken = thunkAPI.getState().auth.accessToken;

            const res = await fetch(`${import.meta.env.VITE_API_URL}/api/users/me`, {
                method: 'GET',
                headers: {
                    Accept: 'application/json',
                    //Authorization: `Bearer ${accessToken}`,
                }
            })
    
            const data = await res.json();
    
            if(res.status === 200){
                return data;
            } else {
                return thunkAPI.rejectWithValue(data);
            }
        } catch(err){
            return thunkAPI.rejectWithValue(err.response.data);
        }
    }

)

the VITE_API_URL in my environ is pointed at localhost:5000.

The whole error disappears if I uncomment out the accessToken and header Authorization but I feel like I shouldn’t need that when I’m using httpOnly and not local storage for tokens and I’m handling the cookie already in my ‘me express router’. Here’s my ‘me router’ for express

import express from 'express';
import fetch from 'node-fetch';

const router = express.Router();

router.get('/api/users/me', async (req, res) => {
const { access } = req.cookies;

    try{
        const apiRes = await fetch(`${process.env.API_URL}/api/users/me`, {
            method: 'GET',
            headers: {
                Accept: 'application/json',
                Authorization: `Bearer ${access}`,
            }
        });
    
        const data = await apiRes.json();
    
        return res.status(apiRes.status).json(data);
    } catch(err){
        return res.status(500).json({
            error: 'Something went wrong when trying to retrieve user'
        });
    }

})

export default router;

then I’m using cookieParser in my index.js and API_URL connects to localhost:8080 tested with postman and it works.

2

Answers


  1. Chosen as BEST ANSWER

    My main express server file using cors. do i need to pass arguments to my cors?

    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    
    dotenv.config();
    
    const app = express();
    
    app.use(cors());
    
    
    app.use(express.json());
    app.use(cookieParser());
    
    
    app.use(loginRoute);
    app.use(logoutRoute);
    app.use(meRoute);
    app.use(registerRoute);
    
    
    app.get('*', (req, res) => { 
        const indexPath = join(__dirname, 'client', 'dist', 'index.html');
        return res.sendFile(indexPath);
    });
    
    const PORT = process.env.PORT || 5000;
    
    app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
    

  2. Configure your App.js or Main express file using CORS or just use the express server itself for fetching the login details from any DB

    import express from 'express';
    const router = express.Router();
    
    router.get('/api/users/me', async (req, res) => {
    
    
        try{
            //If mongo - configure DB connection 
            const apiRes = await loginCollectionName.findOne({someId:ID});
            if(apiRes){
              return res.status(200).json("Login Success");
            }
           
        } catch(err){
            return res.status(500).json({
                error: 'Something went wrong when trying to retrieve user'
            });
        }
    
    })
    
    export default router;
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search