Bonjour à tous j'ai des sousi pour retourner mes donnée de formulaire entre une appli React et mon serveur Synfony. Cela fonctionne avec fetch mais pas avec Axios. Je voudrait faire une page login avec react.
lors de l'envoie de ma requette j'ai l'erreur
[Application] Feb 27 16:22:56 |CRITICA| REQUES Uncaught PHP Exception ErrorException: "Warning: Trying to access array offset on value of type null" at C:\Users\utilisateur\immolier\src\Controller\MessagerieController.php line 225
sur mon serveur Synfony, donc les donneés ne son par retourner.
vpoic mon code react
import { useState, useEffect } from 'react';
import axios from "axios";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import Alert from "@mui/material/Alert";
import Link from "@mui/material/Link";
import Typography from "@mui/material/Typography";
import Container from "@mui/material/Container";
import IconButton from "@mui/material/IconButton";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import { useRouter } from "next/router";
function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [showPassword, setShowPassword] = useState(false);
const handleEmailChange = (event) => {
setEmail(event.target.value);
};
const handlePasswordChange = (event) => {
setPassword(event.target.value);
};
const handleShowPassword = () => {
setShowPassword(!showPassword);
};
const handleClick = (event) => {
event.preventDefault();
axios
.post("https://localhost:8000/messagerie/login", {
email: email,
password: password,
})
.then((response) => {
console.log(response);
if (response.data.status === "success") {
sessionStorage.setItem("loggedIn", true);
sessionStorage.setItem(
"userData",
JSON.stringify(response.data.data)
);
window.location.href = "/dashboard";
const idssession = response.data.data.id;
} else {
setError(response.data.message);
}
})
.catch((error) => {
console.error(error);
});
};
return (
<Box
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
marginTop: "5%",
}}
>
<Container maxWidth="sm">
<form onSubmit={handleClick}>
<Typography
style={{ marginBottom: "20px" }}
variant="h2"
component="h2"
>
Sign in
</Typography>
{error && (
<Alert style={{ marginBottom: "20px" }} severity="error">
{error}
</Alert>
)}
<TextField
type="email"
value={email}
onChange={handleEmailChange}
variant="filled"
id="email"
label="Email address"
fullWidth
style={{ marginBottom: "20px" }}
/>
<TextField
type={showPassword ? "text" : "password"}
value={password}
onChange={handlePasswordChange}
variant="filled"
id="password"
label="Password"
fullWidth
style={{ marginBottom: "20px" }}
InputProps={{
endAdornment: (
<IconButton onClick={handleShowPassword}>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
),
}}
/>
<Button variant="contained" type="submit">
Login
</Button>
<p>
Don't have an account? <Link href="/register">Sign up</Link>
</p>
</form>
</Container>
</Box>
);
}
export default Login;
voici mon controleur sur Synfony:
#[Route('/login', name: 'app_messagerie_login')]
public function login(Request $request, UserPasswordHasherInterface $passwordHasher, ManagerRegistry $doctrine): Response
{
header("access-control-allow-origin: http://localhost:3000"); // cannot be a wildcard, you have to specify the name of the domain making the request here.
header('access-control-allow-headers: content-type');
header("access-control-allow-credentials: true"); // add this header
// On récupère le message
$rest_json = file_get_contents('php://input');
$_POST = json_decode($rest_json, true);
$email = $_POST['email'];
// $email = 'demo1@gmail.com';
$plainPassword = "azerty";
$entityManager = $doctrine->getManager();
// recuperation de 'id de l'annonce
$userRepo = $entityManager->getRepository(User::class);
$user = $userRepo->findOneBy(["email" => $email]);
$test = $passwordHasher->isPasswordValid($user, $plainPassword);
$response = [];
if ($test == true) {
$iduser = $user->getId();
$response =
[
'id' => $iduser,
'username' => 'teste',
'password' => 'teste',
'email' => 'teste',
];
$data = array("status" => "success", "message" => "Account registered successfully.", "data" => $response);
}
// condition pour inserer le lien de l'image d'acceuil
if ($test == false) {
$data = array("status" => "error", "message" => "Account registered successfully.", "data" => $response);
}
return new JsonResponse($data);
}
Pour récupérer les données que tu envois utilise plutôt le mapRequestPayload de symfony 7 :
https://grafikart.fr/tutoriels/symfony-deserialize-2195