Проблема интеграции проекта Spring Boot и проекта ReactJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Проблема интеграции проекта Spring Boot и проекта React

Сообщение Anonymous »

Я разрабатываю этот проект, используя Spring Boot для бэкэнда и React для внешнего интерфейса, я соединил этот интерфейс и серверную часть. Затем регистрация и вход в систему работают без каких-либо ошибок, но когда я собираюсь получить данные для входа в систему для отображения внешнего интерфейса, появляется сообщение об ошибке. Я создал функцию внешнего интерфейса. при нажатии кнопки «Войти/Зарегистрироваться» происходит переход к профилю пользователя, который функционирует в зависимости от роли (ПОЛЬЗОВАТЕЛЬ/ВЛАДЕЛЕЦ/АДМИН). но соответствующие данные пользователя для входа в систему не могут отображаться. Особенность заключается в том, что когда я запускаю этот API в почтальоне, эта функция работает без каких-либо ошибок.
[img]https://i.sstatic .net/MQdnDDpB.jpg[/img]

Код: Выделить всё

import axios from 'axios';
import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom'; // Import useNavigate hook
import ForgotPasswordPopup from '../components/ForgotPasswordPopup';
import EnterCodePopup from '../components/EnterCodePopup';
import ChangePasswordPopup from '../components/ChangePasswordPopup';
import './login.css';
import MailOutlineIcon from '@mui/icons-material/MailOutline';
import LockIcon from '@mui/icons-material/Lock';
import CloseIcon from '@mui/icons-material/Close';
import { GoogleLogin } from '@react-oauth/google'; // Import from @react-oauth/google

export default function Login() {
const [step, setStep] = useState(null);
const navigate = useNavigate(); // Initialize navigate function
const [email, setEmail] = useState(''); // State for email input
const [password, setPassword] = useState('');
const location = useLocation();
const [error, setError] = useState(''); // State to show login errors

// Get the page the user was trying to access before being redirected to login
const redirectTo = location.state?.from?.pathname || '/';  // Defaults to home page if no previous page

const openForgotPassword = () => setStep('forgot');
const openEnterCode = () => setStep('code');
const openChangePassword = () => setStep('change');
const closePopup = () => setStep(null);

// Navigate to the signup page when the signup button is clicked
const handleSignup = () => {
navigate('/signup'); // Navigate to your signup page
};

// Function to handle Google Login success
const handleGoogleSuccess = (response) => {
console.log('Google login successful:', response);
localStorage.setItem('authToken', 'google-auth-token');
navigate(redirectTo);  // Navigate to the intended page after successful login
};

// Function to handle Google Login failure
const handleGoogleFailure = (error) => {
console.log('Google login failed:', error);
// Handle failed login here
};

// Function to go back to the previous page
const handleClose = () => {
navigate(-1); // Navigates back to the previous page
};

// Handle email/password form submission
const handleSignIn = async (e) => {
e.preventDefault();
setError(''); // Reset error message

try {
// Send a POST request to the backend API
const response = await axios.post(${process.env.REACT_APP_API_URL}/SignInUser/SignIn, {
email,
password,
});

const { role, token } = response.data; // Assuming your backend returns a user object with a role

console.log('Email login successful');

// Store authentication token in localStorage
localStorage.setItem('authToken',token); // Assuming the token is returned

// Redirect based on user role
switch (role) {
case 'User':
navigate('/userprofile');
break;
case 'Owner':
navigate('/ownerprofile');
break;
case 'Admin':
navigate('/adminprofile');
break;
default:
navigate('/'); // Fallback in case role is unrecognized
}
} catch (error) {
if (error.response) {
// Handle specific errors based on the response from the backend
if (error.response.status === 401) {
setError('Incorrect email or password');
} else {
setError('Login failed. Please try again.');
}
} else {
setError('Login failed.  Please try again.');
}
}
};

return (



[img]/images/1.png[/img]
Don't have an account?
SIGN UP
[img]/images/1.1.png[/img]

{/* Update CloseIcon to use handleClose on click */}


Don't have an account?
SIGN UP

Sign in Here


 setEmail(e.target.value)} // Update email state
/>

 setPassword(e.target.value)} // Update password state
/>


Forget Your Password?

SIGN IN

{error && 
{error}
}
OR

{/* Use GoogleLogin from @react-oauth/google */}
 (

[img]/images/1.2.png[/img]
Google

)}
/>



{step === 'forgot' && }
{step === 'code' && }
{step === 'change' && }

);
}

Код: Выделить всё

import React,{useState} from 'react';
import NavigationBar from '../../components/NavigationBar';
import Footer from '../../components/Footer';
import UserContent from '../../components/UserProfile/UserContent';
import {Avatar,Typography} from '@mui/material';
import ChatBubbleOutlineIcon from '@mui/icons-material/ChatBubbleOutline';
import StarOutlineIcon from '@mui/icons-material/StarOutline';
import PersonOutlineIcon from '@mui/icons-material/PersonOutline';
import MenuIcon from '@mui/icons-material/Menu';
import './userProfile.css';

const UserProfile = () => {
const [activeMenuItem, setActiveMenuItem] = useState('Profile');
const [isSidebarVisible, setSidebarVisible] = useState(false);

const toggleSidebar = () => {
setSidebarVisible(!isSidebarVisible);
};

return (

{/* Navigation bar at the top */}



{/* Menu icon for small screens */}



{/* Main container with sidebar and content */}

{/* Sidebar Section */}



User

[list]
[*]              className={sidebar-menu-item ${activeMenuItem === 'Profile' ? 'active' : ''}}
onClick={() => setActiveMenuItem('Profile')}
>

Profile

[*]              className={sidebar-menu-item ${activeMenuItem === 'Chats' ? 'active' : ''}}
onClick={() => setActiveMenuItem('Chats')}
>

Chats

[*]              className={sidebar-menu-item ${activeMenuItem === 'Ratings' ? 'active' : ''}}
onClick={() => setActiveMenuItem('Ratings')}
>

Ratings

[/list]



{/* Main Content Section */}

{/* Content can go here */}







);
};
export default UserProfile;

Код: Выделить всё

import axios from 'axios';

// Create an Axios instance with a base URL
const api = axios.create({
baseURL: process.env.REACT_APP_API_URL,
});

// Request interceptor for adding token
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = Bearer ${token};
}
return config;
},
(error) => Promise.reject(error)
);

// Function to fetch all boarding places
export const fetchBoardingPlaces = async () => {
try {
const response = await api.get('/boarding-places');
return response.data;
} catch (error) {
console.error('Error fetching boarding places:', error);
throw new Error('Unable to fetch boarding places.  Please try again later.');
}
};

// Function to fetch a boarding place by ID
export const fetchBoardingPlaceById = async (id) => {
try {
const response = await api.get(/boarding-places/${id});
return response.data;
} catch (error) {
console.error(Error fetching boarding place ${id}:, error);
throw new Error(Unable to fetch boarding place ${id}.);
}
};

// Change user password
export const changePassword = async (newPassword) => {
const token = localStorage.getItem('token'); // Retrieve token
const response = await api.put('/change-password', { password: newPassword }, {
headers: {
Authorization: Bearer ${token},
},
});
return response.data; // Return success message or user data if needed
};

// Fetch user data
export const fetchUserData = async (token, userId) => {
try {
const response = await api.get(/loginuser/${userId}, {
headers: {
Authorization: Bearer ${token},
},
});
return response.data; // Return user data
} catch (error) {
console.error('Error fetching user data:', error);
throw error; // Propagate the error for further handling
}
};

Код: Выделить всё

import React from 'react';
import UserAccount from './UserAccount';
import UserChats from './UserChats';
import UserRatings from './UserRatings';

const UserContent = ({ activeMenuItem }) => {
return (

{activeMenuItem === 'Profile' && }
{activeMenuItem === 'Chats' && }
{activeMenuItem === 'Ratings' && }

);
};

export default UserContent;

Код: Выделить всё

import React, { useState, useEffect } from 'react';
import { TextField, Button, Typography, Container, Grid } from '@mui/material';
import { fetchUserData, changePassword } from '../../apiService'; // Import the API functions

const UserAccount = () => {
const [userData, setUserData] = useState({
userId: '',
email: '',
name: '',
});
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState('');
const [successMessage, setSuccessMessage] = useState('');

useEffect(() => {
const fetchUserDetails = async () => {
try {
const data = await fetchUserData(); // Call API to get user data
setUserData(data);
} catch (error) {
console.error('Error fetching user data:', error);
}
};

fetchUserDetails();
}, []);

const handleChangePassword = async (e) => {
e.preventDefault();
setError('');
setSuccessMessage('');

// Basic validation for password change
if (!newPassword || !confirmPassword) {
setError('Both password fields are required.');
return;
}
if (newPassword !== confirmPassword) {
setError('Passwords do not match.');
return;
}

try {
await changePassword(newPassword); // Call API to update the password
setSuccessMessage('Password changed successfully!');
setNewPassword('');
setConfirmPassword('');
} catch (error) {
setError('Error changing password.  Please try again.');
}
};

return (


User Account


{/* Display user details */}


User ID: {userData.userId}


Email: {userData.email}


Name: {userData.name}



Change Password

 setNewPassword(e.target.value)}
required
/>
 setConfirmPassword(e.target.value)}
required
/>
{error && {error}}
{successMessage && {successMessage}}

Change Password



);
};

export default UserAccount;

Код: Выделить всё

package com.example.testing.controller;

import com.example.testing.dto.LoginUserDto;
import com.example.testing.dto.ReturnLoginUserDto;
import com.example.testing.service.LoginUserService;
import com.example.testing.utill.JWTAuthenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/loginuser")
public class LoginUserController {
@Autowired
LoginUserService service;

@Autowired
JWTAuthenticator jwtAuthenticator;

@PostMapping("/saveLoginUser")
public ResponseEntity saveLoginUser(@RequestBody LoginUserDto loginUserDto){
ReturnLoginUserDto returnLoginUserDto = service.saveLoginUser(loginUserDto);
if (returnLoginUserDto != null) {
return new ResponseEntity("Register Success", HttpStatus.OK);
} else {
return new ResponseEntity("Already regitered with this Email", HttpStatus.CREATED);
}
}
@GetMapping("/{id}")
public ResponseEntity  getLoginUserById(@PathVariable Integer id) {
LoginUserDto loginUserDto = service.getLoginUserById(id);
if (loginUserDto != null) {
return new ResponseEntity(loginUserDto, HttpStatus.OK);
}
return new ResponseEntity("User not found", HttpStatus.NOT_FOUND);
}
}

Код: Выделить всё

package com.example.testing.service;

import com.example.testing.dto.LoginUserDto;
import com.example.testing.dto.ReturnLoginUserDto;
import com.example.testing.entity.LoginUser;
import com.example.testing.repo.LoginUserRepo;
import com.example.testing.utill.SignInMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service

public class LoginUserService {
@Autowired
LoginUserRepo loginUserRepo;
@Autowired
SignInMail signInMail;
@Autowired
PasswordEncoder passwordEncoder;

public ReturnLoginUserDto saveLoginUser(LoginUserDto loginUserDto) {
String encodedPassword = passwordEncoder.encode(loginUserDto.getPassword());

if (loginUserRepo.existsLoginUserByEmail(loginUserDto.getEmail())) {
return null;
}

LoginUser save = loginUserRepo.save(
new LoginUser(loginUserDto.getContactNo(),encodedPassword,loginUserDto.getEmail(),loginUserDto.getRole()));
signInMail.sendEmail(loginUserDto);
return new ReturnLoginUserDto(save.getEmail(), save.getId());
}
public List getAllLoginUser(){
List all = loginUserRepo.findAll();

List loginUserDtos = new ArrayList();
for(LoginUser loginUser : all){
loginUserDtos.add(new LoginUserDto(loginUser.getId(), loginUser.getContactNo(), loginUser.getPassword(), loginUser.getEmail(), loginUser.getRole()));
}
return loginUserDtos;
}
}

Код: Выделить всё

package com.example.testing.entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class LoginUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer contactNo;
private String password;
private String email;
private String role;

@OneToOne(mappedBy = "loginUser", cascade = CascadeType.ALL)
private BoardingOwner boardingOwner;

public LoginUser(Integer contactNo, String password, String email, String role) {
this.contactNo = contactNo;
this.password = password;
this.email = email;
this.role = role;
}

public LoginUser(Integer id, Integer contactNo, String password, String email) {
}
}

Код: Выделить всё

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class LoginUserDto {
private Integer id;
private Integer contactNo;
private String password;
private String email;
public String role;
}
нам нужно показать данные входа пользователя в его собственный профиль, нам нужно знать, как правильно интегрироваться.


Подробнее здесь: https://stackoverflow.com/questions/791 ... on-problem
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Проблема интеграции проекта Spring Boot и проекта React
    Anonymous » » в форуме JAVA
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Проблема интеграции проекта Spring Boot и проекта React
    Anonymous » » в форуме JAVA
    0 Ответы
    8 Просмотры
    Последнее сообщение Anonymous
  • Spring Boot не удалось выполнить цель org.springframework.boot: Spring-Boot-Maven-Plugin: 3.3.0: запустить
    Anonymous » » в форуме JAVA
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Spring Boot не удалось выполнить цель org.springframework.boot: Spring-Boot-Maven-Plugin: 3.3.0: запустить
    Anonymous » » в форуме JAVA
    0 Ответы
    8 Просмотры
    Последнее сообщение Anonymous
  • Spring Boot не удалось выполнить цель org.springframework.boot: Spring-Boot-Maven-Plugin: 3.3.0: запустить
    Anonymous » » в форуме JAVA
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous

Вернуться в «JAVA»