【发布时间】: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