So I am using Laravel 5.8 as an API to a ReactJS view.
I already created a 'cors' middleware, i registered it on Kernel.php file, and I am using it on the api-routes that I am using. I tested using a GET Request and it worked, but when I test with a POST Request, I get the cors error:
Access to fetch at 'http://localhost:8000/api/posts' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
So i have on my api.php ("/routes/api.php"):
Route::get('/posts', 'PostController@index')->middleware('cors');
Route::post('/posts', 'PostController@store')->middleware('cors');
My cors.php middleware:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
}
}
On my Kernel.php ("/app/Http/Kernel.php") I updated the "$routeMiddleware" array with my 'cors' middleware
'cors' => \App\Http\Middleware\Cors::class,
Now in my React project, my api.js (where I made the code to make the requests):
// get Posts
export const getPosts = () => {
return fetch('http://localhost:8000/api/posts')
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err));
}
// create new post
export const createPost = (post) => {
return fetch('http://localhost:8000/api/posts',
{
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
})
.then(res => res.json())
.then(res => console.log(res));
}
I don't understand why everything is working fine when i try the Get request, but when i try the Post Request, i get the CORS error. Someone already had this problem?
Access-Control-Allow-Origin: *is not accepted by browser, you need to specify the domains allowed. no more jokers*