从 React 前端调用 PHP Lumen 后端并解决 CORS 问题

Calling a PHP Lumen Backend from a React frontend and solving the CORS issues

所以基本上我使用 Lumens 作为我的后端 api(在 localhost:8000)。现在在我的前端 React 应用程序(在 localhost:3000)上,我像这样向我的后端发出请求:

fetch(`http://localhost:8000/feedback/add`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                feedback: this.state.feedback,
                email: this.state.email,
            }),
        })

但是,当我向 to/from 不同的服务器发出请求时,我一直 运行 关注 cors 问题。 我一直在谷歌搜索并试图找出解决方案,但似乎有很多不同的想法,例如在 Lumens 中使用中间件(许多不同的解决方案)或设置模式:no-cors 前端。但我真的不知道该怎么办,因为它们似乎仍然会引起进一步的问题。

有没有人有类似的设置?一劳永逸地解决这个问题的方法是什么?

我已经开发了一些使用 Laravel 作为后端的 SPA。默认情况下,Laravel 会保护您免受未经授权的呼叫 API,这听起来就像您 运行 所喜欢的那样。

我建议您使用 composer 安装 Spatie CORS 包以允许从第三方域调用您的后端:

composer require spatie/laravel-cors

此软件包与 Laravel 和 Lumen 兼容。自述文件包含您需要的所有安装说明。

正确安装后,您将能够指定哪些第三方域可以访问您的 API:

'allow_origins' => [

    '*', // all domains are allowed... or set them up individually:

    'https://my-site-1.com',
    'https://my-site-2.com', 
],

Spatie CORS 包:https://github.com/spatie/laravel-cors