vue.js Laravel 9 - CORS不工作(对XMLHttpRequest的访问已被CORS策略阻止)

rkue9o1l  于 2022-11-17  发布在  Vue.js
关注(0)|答案(3)|浏览(192)

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

CORS策略已阻止从源“http://127.0.0.1:8080”访问位于“http://localhost:8000/api”的XMLHttpRequest:请求的资源上不存在“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,

];

前端代码(Vuej)

〉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的浏览器和扩展添加以下标题自动响应:

a)访问控制允许方法:GET、PUT、POST、DELETE、HEAD、选项
B)访问控制允许方法:*

但我认为使用扩展不是一个解决方案,因为我希望不仅在调试模式下,
下面是浏览器中响应的一些屏幕截图。

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

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

3-启用扩展之前的报头响应详情(仅9个报头):

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

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

x1c4d 1x指令集

kb5ga3dv

kb5ga3dv1#

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

czfnxgou

czfnxgou2#

我找到了解决问题的方法,我试图从http://localhost:8000/api获取数据,当我检查cors.php文件时,我发现paths键包含2个值,如下所示:
'paths' => ['api/*', 'sanctum/csrf-cookie']
因此,正如我所说,我正在导航到apipath而不是**api/***only,因此数组应包含“api”的值,如下所示:
'paths' => ['api/*', 'sanctum/csrf-cookie', 'api']

2exbekwf

2exbekwf3#

添加新的中间件应用\Http\Middleware\Cors.php

namespace App\Http\Middleware;

use Closure;

class Cors {
    
    public function handle($request, Closure $next) {
        
        $response = $next($request);
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->headers->set('Access-Control-Allow-Methods', 'POST, GET');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application', 'ip');
        return $response; 
    }
}

将此行添加到app\Http\Kernel.php中

protected $middleware = [
         .....,
        \App\Http\Middleware\Cors::class,
    ];

相关问题