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
My main express server file using cors. do i need to pass arguments to my cors?
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