Search code examples
phplaravelvue.jslaravel-9

Laravel 9 - CORS is not working (Access to XMLHttpRequest has been blocked by CORS policy)


I am trying to build a separated frontend web application using Vuejs and fetching data from Laravel 9 API that I have built, when I try to access the data from the frontend that is the response in the browser console:

Access to XMLHttpRequest at 'http://localhost:8000/api' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The backend code (Laravel 9)

1- api.php file

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Models\User;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::get('/', function () {
    $users = User::all();
    return response()->json($users, 200);
});

2- cors.php file (default configurations)

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

The frontend code (Vuejs)

> 1- main.js file (contains vue setup code)
import { createApp } from 'vue'

import axios from 'axios'
import VueAxios from 'vue-axios'

import App from './App.vue'

const app = createApp(App)

app.use(VueAxios, axios)
app.mount('#app')

2- Users.vue (component that fetches the data)

<template>
  <div class="users">
    test
    <button @click="getUsers()">Get Users</button>
    {{ users }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [],
    }
  },
  methods: {
    getUsers() {
      this.axios.get('http://localhost:8000/api').then((response) => {
        // this.users = response;
        // console.log(this.users);
        console.log(response);
      }).catch(err => console.log('error: ' + err));
    }
  }
}

update: more illustration

I have used a google extension that allow CORS for the browser and the extension add the following headers to response automatically:

a) access-control-allow-methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
b) access-control-allow-methods: *

but I think it is not a solution to use an extension as I want to solve the problem for the production not only in the debugging mode

and the following are some screenshots of the response in the browser.

1- CORS error response in the browser

CORS error response in the browser

2- number of the header responses before enabling the extension (only 9 headers):

number of the header responses before enabling the extension

3- details of header responses before enabling the extension (only 9 headers):

details of response headers before using the extensions

4- number of the header responses after enabling the extension ( 11 headers):

number of the header responses after enabling the extension ( 11 headers)

5- Details of the header responses after enabling the extension ( 11 headers)

enter image description here


Solution

  • I find a solution for my problem, I was trying to fetch data from http://localhost:8000/api and when I checked cors.php file I find the paths key contains 2 values like the following:
    'paths' => ['api/*', 'sanctum/csrf-cookie']
    so like I said I was navigating to api path not api/* only so the array should contain a value of the 'api' like the following:
    'paths' => ['api/*', 'sanctum/csrf-cookie', 'api']