How to import user data

I have a n issue with my React18 app and the backend node + express+ msql. The issue i can get in local Storage the id of the user in the purpose to put it in client page. It’s a new project and i’m again beginer. thank for your help if you see an error. Here is my code :

account.service.js

import Axios from './Caller.service'

let login = (credentials) => {
    return Axios.post('/Auth/login', credentials)
}

let saveToken = (token) => {
    localStorage.setItem('token', token)
}
let saveId = (id) => {
    console.log('Received ID:', id);
  localStorage.setItem('id',`${id}`);
  console.log('Stored ID in localStorage:', localStorage.getItem('id'));
}
const logout = () => {
    return fetch('/logout', {
        method: 'GET'
      })
      .then(response => response.text());
  };

let isLogged = () => {
    let token = localStorage.getItem('token')
    return !!token
}

let getToken = () => {
    return localStorage.getItem('token')
}
export const accountService = {
    login, saveToken, logout, isLogged, getToken, saveId
}

Login.js

import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import Header from '../../component/Header';
import '../../styles/Header.css';
import Footer from '../../component/Footer';
import '../../styles/Global.css';
import './Login.css';
import { accountService } from '../../_services/account.service';


function LoginForm() {
  let navigate = useNavigate()
  const [credentials, setCredentials] = useState ({
    username: '',
    password: '',
    email: ''
  })
   const onChange = (e) => {
      setCredentials ({
        ...credentials,
        [e.target.name]: e.target.value
      })
   }

  
  const handleSubmit = (e) => {
    e.preventDefault();
    
    accountService.login(credentials)
    .then(res => {
      if (res.data.redirect) {
        console.log(res.data)
          accountService.saveToken(res.data.access_token);
          navigate(res.data.redirect, { replace: true });
        }
        // Stockage du token d'authentification dans le localStorage
      accountService.saveToken(res.data.access_token);
      const id = res.data.id;
      accountService.saveId(id);
      console.log(localStorage.getItem('token'));
      console.log(localStorage.getItem('id'));
    })
  
    .catch(error => console.log(error))
  }
  

Client.js

mport React, { useState, useEffect } from 'react';
import Header from '../../component/Header'
import Footer from '../../component/Footer'
import { useNavigate } from 'react-router-dom';
import './Client.css'
import '../../styles/Global.css'
import { accountService } from '../../_services/account.service';
import axios from 'axios';


const Client = () => {
  const navigate = useNavigate();
  const [email, setEmail] = useState('');
  const [username, setUsername] = useState('');
  const [id, setId] = useState('');

  useEffect(() => {
    const userId = localStorage.getItem('id');
    console.log('Stored ID in localStorage:', userId);

    const fetchData = async () => {
      try {
        const response = await axios.get('/api/users/me', { params: { id: userId } });
        console.log('Response data:', response.data);
        
        const user = response.data;
        setEmail(user.email);
        setUsername(user.username);
        setId(user.id);
      
      } catch (error) {
        console.error('Erreur de chargement des données', error);
      }
    };

    fetchData();
  }, []);

And finally the backend server.js

/ Route pour la connexion d'un utilisateur
app.post('/Auth/login', async (req, res) => {
  const { username, password, email } = req.body;

  if (!username || !password || !email) {
    return res.status(400).json({ message: "Veuillez fournir un nom d'utilisateur, un mot de passe et un e-mail." });
  }

  const query = "SELECT * FROM users WHERE username = ? AND email = ?";
  try {
    const [rows] = await pool.query(query, [username, email]);

    if (rows.length === 0) {
      return res.status(401).json({ message: "Nom d'utilisateur, mot de passe ou e-mail incorrect." });
    }

    const user = rows[0];
    const passwordMatch = await bcrypt.compare(password, user.password);

    if (!passwordMatch) {
      return res.status(401).json({ message: "Nom d'utilisateur, mot de passe ou e-mail incorrect." });
    }

    const tokenPayload = {
      id: user.id,
      username: user.username,
      email: user.email
    };
    const token = jwt.sign(tokenPayload, process.env.JWT_SECRET, { expiresIn: '1h' });

    // Set the token as a cookie
    res.cookie('token', token, { httpOnly: true });

    // Check if the user is a client
    const isClient = await checkIfClient(user.id);

    if (isClient) {
      // L'utilisateur est un client, effectuez la redirection appropriée
      res.json({ data: { access_token: token, id: user.id }, redirect: '/client' });
    } else {
      // L'utilisateur est un administrateur, effectuez la redirection appropriée
      res.json({ data: { access_token: token }, redirect: '/admin' });
    }
  } catch (error) {
    console.error(error);
    res.status(500).send("Une erreur est survenue lors de la connexion de l'utilisateur.");
  }
});


// CheckIfclient
const checkIfClient = async (userId) => {
  const query = "SELECT * FROM users WHERE id = ?";
  const [rows] = await pool.query(query, [userId]);
  return rows.length > 0;
};

// Route pour récupérer les informations du profil du client
app.get('/api/users/me', (req, res) => {
  // Valider les données d'entrée
  if (req.query.id === undefined) {
    res.status(400).json({ error: 'Identifiant requis.' });
    return;
  }
  
  // Récupérer les données utilisateur de la base de données
  connection.query('SELECT email, username, id FROM users WHERE id = ?', [req.query.id], (err, rows) => {
    if (err) {
      console.error(err);
      res.status(500).json({ error: 'Récupération des données erronées' });
      return;
    }
  
    // Renvoyer les données utilisateur au client
    res.json(rows[0]);
  });
});

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.