Issue
I need to login in my SPA on React, it work on 127.0.0.1:8000
Laravel working on 127.0.0.1:3000.
When i use axios request, i get error in log in chrome:
Access to XMLHttpRequest at 'http://localhost:8000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
In sanctum.php i added
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,localhost:8000,127.0.0.1:3000,::1',
Sanctum::currentApplicationUrlWithPort()
))),
In .env i write SANCTUM_STATEFUL_DOMAINS=127.0.0.1:3000
and try with SANCTUM_STATEFUL_DOMAINS=127.0.0.1:8000
, but it also didn't work;
In documentation i found information for only domain and subdomain, but i dont work with domains.
Of course I can write in 'cors.php' 'paths' => ['api/*', 'sanctum/csrf-cookie', 'login']
but i think is bad solutions.
Request code axios:
const config={
headers:{
accept:'application/json',
referer:'127.0.0.1:8000/',
'Access-Control-Allow-Origin':'*'
}
}
function fetchCookie(){
const response = axios.get('http://localhost:8000/sanctum/csrf-cookie')
const response1 = axios.post('http://localhost:8000/login',loginData,config)
console.log(response1);
}
Therefore, where and what should I write to make it work for me.
Apologies in advance for my English
Solution
Needed create a middleware how answered @RaphaelRafatpanah and added in it headers.
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', 'http://127.0.0.1:3000');
$response->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
$response->header('Access-Control-Allow-Headers', 'x-xsrf-token,Content-Type,withcredentials');
$response->header('Access-Control-Allow-Credentials', 'true');
return $response;
}
These headers will solve the initial errors and subsequent.
Answered By - Yurei Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.