laravel 10 的 CORS 问题

问题描述 投票:0回答:1

我正在使用 Laravel 创建一个项目,该项目必须连接到使用 React 创建的前端。我将后端托管在 000webhost 上,但当我尝试进行 api 调用时,它给出了 CORS 错误。我读到,对于 Laravel 10,你不再使用 Fruitcake/laravel-cors,而是使用

 \Illuminate\Http\Middleware\HandleCors::class 

app/Http/Kernel.php 文件。我已经这样做了,但它总是给我同样的错误。我该如何解决?

我需要在路由中指定中间件还是自动应用?

错误 跨源请求被阻止:源匹配策略不允许从 https://expense-api.000webhostapp.com/api/login 读取远程资源。原因:CORS 请求失败。状态码:(空)。

laravel cors
1个回答
0
投票

您的配置目录中有一个名为 cors.php 的文件。在那里,您可以配置跨域资源共享的设置|或“CORS”,如您所愿。

让我分享我自己的副本来指导您完成它。

<?php

返回[

/*
|--------------------------------------------------------------------------
| 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' => [
    'your frontend/react/vue app URL here',
    'http://localhost:3000',
    '*'
],

'allowed_origins_patterns' => [],

'allowed_headers' => [':authority:', ':method:', ':path:', ':scheme:','*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false,
];

这会将这些 URL 列入白名单并解决您的 CORS 问题。

© www.soinside.com 2019 - 2024. All rights reserved.