0

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;
  • See https://stackoverflow.com/a/39999421/11667949 – Shivam Jha Dec 28 '22 at 13:08
  • hi thanks for the answer. im not using webpack and the image isnt on the react project its in the server i built so i cant import or require from react. – Reef Goldberg Dec 28 '22 at 13:27
  • What did `console.log(userInfo?.avatar)` print ? – Shivam Jha Dec 28 '22 at 13:30
  • Buzi.png which is the end point of the file and i added the local host before that ```src={`http://localhost:8080/uploads/${userInfo?.avatar}` ``` – Reef Goldberg Dec 28 '22 at 13:32
  • Again, "What did console.log(userInfo?.avatar) print ?" – Shivam Jha Dec 28 '22 at 13:32
  • it logged Buzi.png – Reef Goldberg Dec 28 '22 at 13:33
  • I am assuming you server runs locally on different port than you client (frontend) ? – Shivam Jha Dec 28 '22 at 13:35
  • yes my react dev project runs on localhost:3000 and server on localhost:8080 – Reef Goldberg Dec 28 '22 at 13:36
  • Seems it is not happening due to CORS issues. Is there any error logged into your browser's console when you open your react app ? – Shivam Jha Dec 28 '22 at 13:37
  • ive required cors in my node.js server but sometimes the console logs me this error ``` Uncaught TypeError: Cannot read properties of null (reading 'avatar') ``` – Reef Goldberg Dec 28 '22 at 13:42
  • Now that when you use `userInfo` (`userInfo?.avatar`), this error should have got removed, or is it caused by some other code ? – Shivam Jha Dec 28 '22 at 13:43
  • @ReefGoldberg is the syntax error at your commented `src` attribute the same as in your project? If so you are missing a closing curly brace `}` at the end. – Aleksandar Dec 28 '22 at 13:48
  • still the same error but not on every render, cant tell why. and i dont have a syntax error in my code otherwise i would get an error for that. its only in the post i wrote up there – Reef Goldberg Dec 28 '22 at 13:50
  • You should post the part of your code where you assign a value to `userInfo.avatar`. Also by the current logic, what happens if you modify your condition to: `{!token && !userInfo.avatar ? (...` – Aleksandar Dec 28 '22 at 14:03
  • @Aleksandar thanks for the comment i've edited my post hope it will be better to understand the issue. and if i modify the logic you wrote here it stays the same. – Reef Goldberg Dec 28 '22 at 14:13

0 Answers0