I am working on a user registration feature with frontend React and backend Laravel 8. When the input fields are valid it is working fine. But even if any of the input fields fail in the backend validation it throws an error saying "access has been blocked by CORS policy". Here is an image of the error. My question is why is everything working fine when the input fields are valid, but throwing an unrelatable error when it fails. And below is my code:
Frontend (React)
const register = async(values) => {
const {email, serial, password, confirm_password} = values;
const details = {email : email, serial : serial, password: password, password_confirmation : confirm_password};
try {
const result = await fetch('http://192.168.1.15:8000/api/v1/register', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(details),
})
const data = await result.json();
if (data.error) {
console.log(data.error)
}
else {
setUser(data.data)
cookies.set('Noortap', data.data, { path: '/' });
console.log(cookies.get('Noortap'))
}
}
catch (err) {
console.log(err)
}
}
Backend (Laravel)
public function register(Request $request)
{
$request->validate([
'name' => 'max:255',
'email' => 'required|unique:users,email|email|max:255',
'serial' => ['required','max:255', new IsValidSerialNumber],
'password' => 'required|confirmed',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'is_admin' => 0,
'password' => Hash::make($request->password)
]);
\App\Models\Tag::where('serial_number', $request->serial)->update([
'assigned' => 1,
'user_id' => $user->id
]);
// // response
// return $this->login($request);
return $request;
}
CodePudding user response:
That is because your frontend and backend are on separate "domains". In this case, they are on the same domain but a different port. You will need to add http://192.168.1.15:3000 to the $except array in app/Http/Middleware/VerifyCsrfToken.php so that you dont face a CORS policy issue.
So your file should look something like this:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
'192.168.1.15:3000'
];
}
CodePudding user response:
you need to add this to the top of your main routes.php file:
header('Access-Control-Allow-Origin: 'http://192.168.1.15:8000');
or when I want cross browser access I add a .htaccess file into the folder where my endpoint is with the following in it:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
