Trying to use fetch and pass in mode: no-cors

后端 未结 6 852
悲&欢浪女
悲&欢浪女 2020-11-22 02:33

I can hit this endpoint, http://catfacts-api.appspot.com/api/facts?number=99 via Postman and it returns JSON

Additionally I am using create

6条回答
  •  没有蜡笔的小新
    2020-11-22 03:32

    So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:

    1. In your Laravel project, run command php artisan make:middleware Cors. This will create app/Http/Middleware/Cors.php for you.
    2. Add the following code inside the handles function in Cors.php:

      return $next($request)
          ->header('Access-Control-Allow-Origin', '*')
          ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
      
    3. In app/Http/kernel.php, add the following entry in $routeMiddleware array:

      ‘cors’ => \App\Http\Middleware\Cors::class
      

      (There would be other entries in the array like auth, guest etc. Also make sure you're doing this in app/Http/kernel.php because there is another kernel.php too in Laravel)

    4. Add this middleware on route registration for all the routes where you want to allow access, like this:

      Route::group(['middleware' => 'cors'], function () {
          Route::get('getData', 'v1\MyController@getData');
          Route::get('getData2', 'v1\MyController@getData2');
      });
      
    5. In Vue front-end, make sure you call this API in mounted() function and not in data(). Also make sure you use http:// or https:// with the URL in your fetch() call.

    Full credits to Pete Houston's blog article.

提交回复
热议问题