9

理解できません。私は何時間もこれに苦労しています

Laravel で Vue.js を使用しており、外部 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ヘッダーを追加しようとしました

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

同じ結果/エラーで。

誰かが私が間違っていることを教えてもらえますか?

4

2 に答える 2

7

ミドルウェアから CORS ヘッダーを設定する必要があります。たぶん、追加の設定が必要ですか?

handle()とにかく、独自のミドルウェアを作成し、次の例のようにメソッドで CORS ヘッダーを設定できます。

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 クラスのグローバル$middleware配列 ( の下) に追加すると、準備完了です。CheckForMaintenanceMode::class

于 2016-06-16T14:54:06.537 に答える