【问题标题】:Vuejs and Laravel Post Request CORSVuejs 和 Laravel 发布请求 CORS
【发布时间】:2016-10-18 01:39:08
【问题描述】:

我不明白。几个小时以来我一直在努力解决这个问题

我将 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 Package,并将中间件添加到我的路由中,例如

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

同样的结果/错误。

谁能告诉我我做错了什么?

【问题讨论】:

    标签: laravel cors vue.js vue-resource


    【解决方案1】:

    您需要从中间件设置 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 下),您应该一切顺利。

    【讨论】:

    • 如果这没有帮助,就像它在 Laravel 5.5+ 中对我不起作用一样,还请检查您的config/cors.php,您可能还需要在那里设置允许的来源、标题和方法.
    【解决方案2】:

    其他方式(不创建新的 laravel 中间件)是在您的 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');
    

    并在 vue 上的拦截器之前添加: Vue.http.options.crossOrigin = true

    【讨论】:

      猜你喜欢
      • 2017-07-10
      • 2017-04-21
      • 2020-02-28
      • 2017-05-20
      • 2018-07-18
      • 2016-02-07
      • 2019-10-03
      • 2018-08-07
      相关资源
      最近更新 更多