9

我不明白。几个小时以来我一直在为此苦苦挣扎

我将 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 无法加载 https://www.mollie.com/payscreen/select-method/JucpqJQses。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问来源“ https://payment.dev ”。

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

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'] = '*';

具有相同的结果/错误。

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

4

2 回答 2

7

You need to set up the CORS headers from the middleware. Maybe you need some extra setup?

Anyway, you can create your own middleware and set up the CORS headers in the handle() method like the following example:

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.
}

Add your custom middleware to the global $middleware array (under CheckForMaintenanceMode::class) in the Kernel.php class and you should be good to go.

于 2016-06-16T14:54:06.537 回答
0

Other way (without creating a new laravel middleware) is add these headers at the begining of your routes.php

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');

and add this before your interceptors on vue: Vue.http.options.crossOrigin = true

于 2016-10-23T04:46:47.743 回答