gula Posted April 15, 2023 Share Posted April 15, 2023 I have made a login page using reactjs as my frontend, php as my backend and mysql as my database but there seems to be something wrong that I can't seem to figure it out so please help This is my frontend import React, { useState } from 'react'; import './css/Login.css'; import { Link } from 'react-router-dom'; function Login() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const handleEmailChange = (event) => { setEmail(event.target.value); }; const handlePasswordChange = (event) => { setPassword(event.target.value); }; const handleSubmit = async (e) => { e.preventDefault(); try { // Make an API call to your backend service or database to validate the email and password const response = await fetch('http://localhost:80/api/login.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email, password }), }); // Handle the response and perform appropriate actions if (response.ok) { // If response is successful, perform login action // e.g. redirect to dashboard or set authentication state console.log('Login successful'); } else { // If response is not successful, display error message setError('Invalid email or password'); } } catch (error) { // Handle any errors that may occur during the API call console.error('Login error:', error); setError('Failed to login. Please try again later.'); } }; return ( <div className="login-container"> <h1 className="login-heading">Login</h1> <form onSubmit={handleSubmit} className="login-form"> <div> <label htmlFor="email" className="login-label"></label> <input type="email" placeholder='Email' id="email" value={email} onChange={handleEmailChange} className="login-form-input" /> </div> <div> <label htmlFor="password" className="login-label"></label> <input type="password" placeholder='Password' id="password" value={password} onChange={handlePasswordChange} className="login-form-input" /> </div> <button type="submit" className="login-button">Login</button> {error && <p className="login-error">{error}</p>} <p className="login-text">New to?</p><Link to="/Register" className="login-link">Register</Link> </form> </div> ); } export default Login; This is my backend <?php header('Access-Control-Allow-Origin: http://localhost:3000'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Requested-With, Accept'); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = json_decode(file_get_contents('php://input'), true); $email = $data['email']; $password = $data['password']; $conn = mysqli_connect('localhost', 'root', '', 'realestate1'); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $query = "SELECT * FROM `registration` WHERE `email` = ?"; $stmt = mysqli_prepare($conn, $query); mysqli_stmt_bind_param($stmt, "s", $email); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); $storedPassword = $row['password']; if (password_verify($password, $storedPassword)) { http_response_code(200); echo json_encode(['message' => 'Login successful']); } else { echo json_encode(['error' => 'Invalid email or password']); } } else { echo json_encode(['error' => 'Invalid email or password']); } mysqli_stmt_close($stmt); mysqli_close($conn); } else { http_response_code(400); echo json_encode(['error' => 'Bad Request']); } ?> This is my database table Quote Link to comment https://forums.phpfreaks.com/topic/316138-the-login-page-is-not-working-please-help/ Share on other sites More sharing options...
gizmola Posted April 15, 2023 Share Posted April 15, 2023 Need more information other than "something is wrong". What exactly is not working the way you expect? Do you get any errors? Some obvious things that jump out are: await fetch('http://localhost:80/api/login.php' Just use a relative url here: await fetch('/api/login.php' This header does not make sense for development. header('Access-Control-Allow-Origin: http://localhost:3000'); Start with something permissive and determine later if you can lock it down. header('Access-Control-Allow-Origin: *'); Why are you posting the data as json? JSON is great for javascript, but has no value for PHP. I would recommend just making a standard post structure. Then you can dispense with having to json_decode it and you can use the $_POST superglobals. $email = isset($_POST['email']) ? isset($_POST['email']) : ''; $password = isset($_POST['password']) ? isset($_POST['password']) : ''; At any rate, when you return json, you need to set the Content-type if ($_SERVER['REQUEST_METHOD'] === 'POST') { header("Content-Type: application/json"); Last but not least, remove any PHP end tags. End tags are never a good idea, and only should be used in a script where you need to mix html and PHP together. You should never end a script with a php end tag. See PSR-12 for this and other coding standard recommendations. Quote Link to comment https://forums.phpfreaks.com/topic/316138-the-login-page-is-not-working-please-help/#findComment-1607352 Share on other sites More sharing options...
gula Posted April 16, 2023 Author Share Posted April 16, 2023 19 hours ago, gizmola said: Need more information other than "something is wrong". What exactly is not working the way you expect? Do you get any errors? Some obvious things that jump out are: await fetch('http://localhost:80/api/login.php' Just use a relative url here: await fetch('/api/login.php' This header does not make sense for development. header('Access-Control-Allow-Origin: http://localhost:3000'); Start with something permissive and determine later if you can lock it down. header('Access-Control-Allow-Origin: *'); Why are you posting the data as json? JSON is great for javascript, but has no value for PHP. I would recommend just making a standard post structure. Then you can dispense with having to json_decode it and you can use the $_POST superglobals. $email = isset($_POST['email']) ? isset($_POST['email']) : ''; $password = isset($_POST['password']) ? isset($_POST['password']) : ''; At any rate, when you return json, you need to set the Content-type if ($_SERVER['REQUEST_METHOD'] === 'POST') { header("Content-Type: application/json"); Last but not least, remove any PHP end tags. End tags are never a good idea, and only should be used in a script where you need to mix html and PHP together. You should never end a script with a php end tag. See PSR-12 for this and other coding standard recommendations. By something is wrong by I mean it is not woring at intended, the console is priniting login successful even though I enter wrong email and password Quote Link to comment https://forums.phpfreaks.com/topic/316138-the-login-page-is-not-working-please-help/#findComment-1607372 Share on other sites More sharing options...
requinix Posted April 17, 2023 Share Posted April 17, 2023 10 hours ago, gula said: By something is wrong by I mean it is not woring at intended, *slow clap* 10 hours ago, gula said: the console is priniting login successful even though I enter wrong email and password response.ok will always be true as long as your endpoint is returning 200. If you want to use response.ok then you have to send a non-200 on failure. 1 Quote Link to comment https://forums.phpfreaks.com/topic/316138-the-login-page-is-not-working-please-help/#findComment-1607388 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.