我不明白。几个小时以来我一直在为此苦苦挣扎
我将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标头
Vue.http.headers.common['Access-Control-Allow-Origin'] = '*';
Vue.http.headers.common['Access-Control-Request-Method'] = '*';
结果/错误相同。
有人可以告诉我我做错了吗?
您需要从中间件设置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
),您应该一切顺利。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句