I have an React App which fetch api(the code below) from a backend Server which is in Laravel(PHP).
export const createVenue = (venueData) => dispatch => {
console.log('action called');
fetch('http://localhost:8001/api/venues', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
venueData
})
})
.then(res=>res.json())
.then(venue=>
dispatch({
type: NEW_VENUE,
payload: venue
})
);
};
And I have set a Middleware with routes on server to accept CORS request as below:
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');
}
}
Here are the routes:
Route::group(['prefix' => 'api/','middleware' => 'cors'], function() {
Route::get('venues',[
'as' => 'apiVenueGet',
'uses' => 'Api\Venue@index'
]);
Route::post('venues',[
'as' => 'apiVenuePost',
'uses' => 'Api\Venue@create'
]);
});
But when i am using to submit form I am getting this in console of browser:
Failed to load http://localhost:8001/api/venues: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Now the problem can get solved if I Use following header in my fetch call:
headers: {
'Accept': 'text/plain',
'Content-Type': 'application/json'
},
or with x-form-urlencode,
can anybody explain why application/json doesnt work here?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire