问题
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?
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/37860851/vuejs-and-laravel-post-request-cors