【问题标题】:Laravel 9 - CORS is not working (Access to XMLHttpRequest has been blocked by CORS policy)Laravel 9 - CORS 不起作用(对 XMLHttpRequest 的访问已被 CORS 策略阻止)
【发布时间】:2022-10-23 15:40:43
【问题描述】:

我正在尝试使用构建一个分离的前端 Web 应用程序Vuejs并从中获取数据Laravel 9 API我构建的,当我尝试从浏览器控制台中的响应前端访问数据时:

从源“http://127.0.0.1:8080”访问“http://localhost:8000/api”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头出现在请求的资源。

后端代码(Laravel 9)

1- api.php 文件

<?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 文件(默认配置)

<?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,

];

前端代码(Vuejs)

> 1- main.js 文件(包含 vue 设置代码)
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(获取数据的组件)

<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));
    }
  }
}

更新:更多插图

我使用了允许浏览器使用 CORS 的 google 扩展程序,并且该扩展程序添加了以下标头以自动响应:

a) 访问控制允许方法:GET、PUT、POST、DELETE、HEAD、OPTIONS
b) 访问控制允许方法:*

但我认为这不是使用扩展的解决方案,因为我不仅要在调试模式下解决生产问题

以下是浏览器中响应的一些截图。

1- 浏览器中的 CORS 错误响应

2- 启用扩展之前的标头响应数(仅 9 个标头):

3-启用扩展之前的标头响应详细信息(仅 9 个标头):

4-启用扩展后的标头响应数(11个标头):

5-启用扩展后标头响应的详细信息( 11个标题)

【问题讨论】:

  • 您是否有可能在后端遇到问题?检查请求时,您可以在网络选项卡中发布屏幕截图或详细信息吗?
  • 我对 laravel 了解不多,但可能是 cors.php 路径中的斜杠导致了问题。您的客户正在请求 http://localhost:8000/api,也许尝试在 cors 路径中添加“api”。
  • 我已经用有关浏览器响应的更多详细信息更新了问题
  • cors.php 根本没有帮助

标签: php laravel vue.js laravel-9


【解决方案1】:

我个人在将 NuxtJs 连接到 Laravel API 时遇到了同样的问题。 在 Laravel cors.php 文件中,我所做的只是将“supports_credentials”的值设置为 true。默认值为“假”。 我希望它可以节省您的时间。

【讨论】:

    【解决方案2】:

    我找到了解决问题的方法,我试图从中获取数据http://localhost:8000/api当我检查 cors.php 文件时,我发现路径键包含 2 个值,如下所示:
    'paths' =&gt; ['api/*', 'sanctum/csrf-cookie']
    所以就像我说的我正在导航到api路径不接口/* 只有这样,数组才应该包含一个 'api' 的值,如下所示:
    'paths' =&gt; ['api/*', 'sanctum/csrf-cookie', 'api']

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2019-12-18
      • 2022-08-14
      • 2020-05-05
      • 2020-03-12
      • 2019-04-28
      • 2021-10-27
      • 2019-08-20
      相关资源
      最近更新 更多