I’m facing this problem at Laravel 11 update. When I was using Laravel 10, my API requests from React frontend to Laravel backend works well without any problem.
This is the axios-client.js that I set up
import axios from "axios";
const axiosClient = axios.create({
baseURL: `${import.meta.env.VITE_API_BASE_URL}/api`
})
axiosClient.interceptors.request.use( (config)=> {
const token = localStorage.getItem('ACCESS_KEY')
config.headers.Authorization = `Bearer ${token}`
return config;
})
axiosClient.interceptors.response.use ((response) => {
return response;
}, (error)=>{
const {response} = error;
if(response.status === 401) {
localStorage.removeItem('ACCESS_TOKEN');
} else {
throw error;
}
})
export default axiosClient
This is my Signup.jsx React component that I’m using to send api request to my Laravel backend
import { useRef } from "react";
import { Link } from "react-router-dom";
import axiosClient from "../axios-client.js";
import { useStateContext } from "../components/contexts/ContextProvider";
export default function Signup(){
const nameRef = useRef();
const emailRef = useRef();
const passwordRef = useRef();
const passwordConfirmationRef = useRef();
const { setUser , setToken } = useStateContext() ;
const onSignUp = (ev) => {
ev.preventDefault()
const payLoad = {
name:nameRef.current.value,
email:emailRef.current.value,
password:passwordRef.current.value,
password_confirmation:passwordConfirmationRef.current.value,
}
//console.log(payLoad); see in chrome inspect
//now sending information to Laravel
axiosClient.post("/signup", payLoad)
.then (({data})=> {
setUser(data.user);
setToken(data.token);
})
.catch (err => {
const response = err.response;
if (response && response.status === 422 ){
console.log(response.data.errors)
}
})
}
return (
<div className="login-signup-form animated fadeInDown">
<div className="form">
<form onSubmit={onSignUp}>
<h1 className="title"> Create an account</h1>
<input ref={nameRef} placeholder="Full Name" />
<input ref={emailRef} type="email" placeholder="E-mail" />
<input ref={passwordRef} type="password" placeholder="Password"/>
<input ref={passwordConfirmationRef} type="password" placeholder="Password Comfirmation"/>
<button className="btn btn-block">Sign Up</button>
<p className="message">
Already Registered? <Link to="/login">Login into your account</Link>
</p>
</form>
</div>
</div>
)
}
This works fine with Laravel 10 , but now in Laravel 11
This error shows up and I don’t know how to solve it.
enter image description here
My backend Laravel api.php route and functions are working fine but React API request won’t just go out beacause of above error shown in image. (I will upload them to show too if it’s necessary.)
Any way to solve this ?
To solve the React api request to Laravel 11 CORS error.
Arkar Tin Myint is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1