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

我正在使用Vue.与Laravel一起使用js,并try 向外部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)
                });
            }
        }

ERROR

无法加载MLHttpRequest

我为我的后端安装了Laravel CORS Package,并将中间件添加到我的路由中,例如

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

但我仍然得到了错误.我还try 添加带有

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.
}

将自定义中间件添加到内核中的全局$middleware数组(CheckForMaintenanceMode::class以下).php课程,你应该准备好了.

Vue.js相关问答推荐

为什么 Vue 在将设置脚本中的计算(computed)属性渲染到模板时找不到变量

如果似乎没有明确使用输入事件,那么发出输入事件有什么作用?

Vue 脚本标签中更漂亮的 destruct 功能

如何在vue中动态加载组件

如何将 axios/axios 拦截器全局附加到 Nuxt?

在基于 TypeScript 的 Vue 中将 vuex 状态和Mutations绑定到复选框组件属性

为什么当我 Select 第二个输入框时音译transliteration不起作用?

vue-router的router-link实际刷新?

vue-test-utils:无法覆盖属性 $route,这通常是由于插件将该属性添加为只读值

使用 Vue.js 的用户可切换自定义主题

SassError:媒体查询表达式必须以(开头

如何使用 Vuejs 和 Laravel 获取当前经过身份验证的用户 ID?

Vue 3 组合 API,如何在 setup() 函数中获取上下文父属性?

Vuetify v-btn 路由活动类问题

使用 Vue-cli,我在哪里声明我的全局变量?

为什么 Vue.js 使用 VDOM?

Vue如何将动态ID与v-for循环+字符串中的字段连接起来?

Vue Chart.js - 条形图上的简单点/线

脚本npm run dev和npm run watch是做什么用的?

Vue过滤器应该如何使用typescript绑定?