Vuejs 和 Laravel Post 请求 CORS

Vuejs and Laravel Post Request CORS

我不明白。我几个小时以来一直在努力解决这个问题

我正在使用 Vue.js 和 Laravel 并尝试向外部 API.

发出 POST 请求

但我的 Vue POST 请求

上总是出现 CORS 错误
methods: {
            chargeCustomer(){
                this.$http.post('/api/chargeCustomer', this.payment).then(function (response) {
                    console.log(response.data)
                },function (response) {
                    console.log(response.data)
                });
            }
        }

错误

MLHttpRequest cannot load https://www.mollie.com/payscreen/select-method/JucpqJQses. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://payment.dev' is therefore not allowed access.

我为我的后端安装了 Laravel CORS Package 并将中间件添加到我的路由中,例如

Route::group(['middleware' => 'cors'], function(){
    Route::post('/api/chargeCustomer', 'Backend\PaymentController@chargeCustomer');
});

但我仍然遇到错误。我还尝试添加 Vue Headers 和

Vue.http.headers.common['Access-Control-Allow-Origin'] = '*';
Vue.http.headers.common['Access-Control-Request-Method'] = '*';

同result/error.

有人能告诉我我做错了什么吗?

您需要从中间件设置 CORS headers。也许您需要一些额外的设置?

无论如何,您可以创建自己的中间件并在 handle() 方法中设置 CORS headers,如下例所示:

public function handle($request, Closure $next) 
{
    return $next($request)
           ->header('Access-Control-Allow-Origin', 'http://yourfrontenddomain.com') // maybe put this into the .env file so you can change the URL in production.
           ->header('Access-Control-Allow-Methods', '*') // or specify `'GET, POST, PUT, DELETE'` etc as the second parameter if you want to restrict the methods that are allowed.
           ->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization') // or add your headers.
}

将您的自定义中间件添加到 Kernel.php class 中的全局 $middleware 数组(在 CheckForMaintenanceMode::class 下),您应该可以开始了。

其他方法(无需创建新的 laravel 中间件)是在 routes.php

的开头添加这些 headers
header('Access-Control-Allow-Origin:  *');
header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization');

并在 vue 的拦截器之前添加: Vue.http.options.crossOrigin = true