Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs and Laravel Post Request CORS

I dont get it. I am struggling with this since hours

I am using Vue.js with Laravel and try to make a POST Request to an external API.

But i am always getting a CORS error on my Vue POST Request

methods: {
            chargeCustomer(){
                this.$http.post('/api/chargeCustomer', this.payment).then(function (response) {
                    console.log(response.data)
                },function (response) {
                    console.log(response.data)
                });
            }
        }

ERROR

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.

I installed the Laravel CORS Package for my Backend and added the middleware to my route e.g

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

But i am still getting the error. I also tried to add the Vue Headers with

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

With the same result/error.

Could someone tell me what i am doing wrong?

like image 949
bobbybackblech Avatar asked Jun 16 '16 13:06

bobbybackblech


1 Answers

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.

like image 90
Davor Minchorov Avatar answered Sep 19 '22 15:09

Davor Minchorov