I was developing my web app with react and I got stuck in the login section. My code was supposed to get the form inputs from the frontend to back end and then sort the data but the issue is that after I click submit, i get the error in the title. Here is login.js
import React, { useState } from "react";
import{ Link } from "react-router-dom";
function Login() {
const [userPass, setUserPass] = useState('');
const [userName, setUserName] = useState('');
const [message, setMessage] = useState('');
function handleUserName(e){
setUserName(e.target.value);
}
function handleUserPass(e){
setUserPass(e.target.value);
}
const handleSubmit = async (e) => {
try{
const response = await fetch('http://localhost:8000/login-m.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: userName,
password: userPass
})
});
const data = await response.json();
if(data.state === 'loggedin'){
window.location.href = "/center";
}
else {
setMessage(data.message);
}
}catch(err){
console.log(err);
}
}
return <>
<h2>
<i className="fa-solid fa-pen-to-square" /> Login
</h2>
<form method="post" onSubmit={handleSubmit}>
<input
type="text"
name="user"
placeholder="Username / Mail"
minLength={3}
maxLength={16}
value={userName}
onChange={handleUserName}
/>
<br />
<input type="password" name="password" placeholder="Password" value={userPass} onChange={handleUserPass}/>
<br />
<input type="submit" placeholder="Submit" />
</form>
<p>{message}</p>
<p>New to crumbs? | <Link to="/register">Register</Link></p>
</>;
};
export default Login;
Here is login-m.php:
<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=utf-8');
function setResponse($state, $message, $user = []){
$response =
[
'state' => $state,
'message' => $message,
'user' => $user
];
echo (json_encode($response));
}
$conn = mysqli_connect('192.168.1.102', 'root', '', 'database');
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$sql = "SELECT * FROM account WHERE user='$user'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) === 1) {
$row = mysqli_fetch_assoc($result);
if(password_verify($password, $row['password']))
{
$_SESSION['user'] = $user;
$message = 'Logged in';
$state = 'loggedin';
setResponse($state, $message, $_SESSION['user']);
}
else
{
$message = 'Wrong password.';
setResponse('error', $message, []);
echo $message;
}
}
else
{
$message = 'Account not found.';
setResponse('error', $message, []);
echo $message;
}
}
}
?>
I made sure that CORS flags are set.