I am using react as front-end and sending request from localhost:3000/contact
to my API that is in laravel http://localhost:8000/create
I am seeing this error:
Access to XMLHttpRequest at 'http://localhost:8000/create' 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. main.1eda3b0ea85babe00767.hot-update.js:183 AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
I have tried using proxy but then the error is 404 and request url becomes: localhost:3000/create
I double checked the proxy that was:
"proxy":"http://localhost:8000"
Code in Contact.jsx is:
axios.post('http://localhost:8000/create', data)
and in laravel:
Route::post('/create', [crudController::class, 'store']);
Controller code:
public function store(Request $request)
{
// var_dump("asdf").die();
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required',
'message' => 'required',
]);
//var_dump($validator).die();
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 400);
}
$project = new form();
$project->name = $request->input('name');
$project->email = $request->input('email');
$project->message = $request->input('message');
//var_dump($project).die();
if ($project->save()) {
return response()->json(['Data inserted successfully' => true, 'data' => $project], 200);
} else {
return response()->json(['error' => 'Unable to create project'], 500);
}
}
I have tested it with POSTMAN and it is working fine with that.