React.js Node.js Multer Axios MongoDb
Hi im trying to load an image i uploaded to to server in my React.js project.
ive made a route to my public folder in the server
app.use("/uploads", express.static("public/uploads/images/"));
and when i enter the http://localhost:8080/uploads/ + file name.png i can see the uploaded img, but in my React project when i enter it as the img src it does not appear.
ive tried it through userInfo?.avatar data i get from MongoDB and server and through hard coding the full domain.
{!token ? (
<HiOutlineUserCircle
className="fs-1 pointer"
data-bs-toggle="dropdown"
aria-expanded="false" />
) : (
<img
src="http://localhost:8080/uploads/buzi.PNG"
// src={`http://localhost:8080/uploads/${userInfo?.avatar}`}
alt={userInfo?.avatar} />
)}
creating auto login hook
const useAutoLogin = () => {
const dispatch = useDispatch();
const autoLoginFunction = async (token) => {
try {
let dataFromToken = jwt_decode(token);
let { data } = await autoLogin();
if (data) {
dispatch(authActions.login(dataFromToken.id));
dispatch(authActions.updateUserInfo(data));
return true;
}
} catch (err) {
return false;
}
};
return autoLoginFunction;
};
export default useAutoLogin;
Auto login function from useAutoLogin hook
import axios from "axios";
const autoLogin = () => {
return axios.get("/auth/getUserById");
};
export default autoLogin;
assigning user info the info of the user from login
const userInfo = useSelector((state) => state.auth.userInfo);
Redux state mangment for login and user info
import { createSlice } from "@reduxjs/toolkit";
//create variable that we want redux to store for us
//this object configure the redux "state"
const initialAuthState = {
loggedIn: false,
isAdmin: false,
userData: null,
userInfo: null,
stay: false,
};
const authSlice = createSlice({
name: "auth",
initialState: initialAuthState,
reducers: {
login(state, action) {
state.loggedIn = true;
state.userData = action.payload;
state.isAdmin = action.payload.isAdmin;
},
logout: (state) => initialAuthState,
updateUserInfo(state, action) {
state.userInfo = action.payload;
},
stayLoggedIn: (state, action) => {
state.stay = action.payload;
},
},
});
export const authActions = authSlice.actions;
export default authSlice.reducer;