【问题标题】:jQuery Select2 Blocked By CORS Policy in Laravel VueLaravel Vue 中的 CORS 策略阻止了 jQuery Select2
【发布时间】:2021-09-29 14:39:01
【问题描述】:

我正在尝试在 Laravel Vue 中使用 jQuery Select2。但是当我使用我的基本网址时,我在下面出现错误。但是,当我使用像https://countriesnow.space/api/v0.1/countries/population/cities 这样的另一个API 服务时,没关系,可以检索数据。怎么了?我一直在尝试解决这个问题,但没有任何效果。

Access to XMLHttpRequest at 'http://localhost/my-project/laravue/api/staff/categories/search-sub-categories/?_type=query' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. 

路线

Route::get('categories/search-sub-categories/{id}', [CategoryController::class, 'searchSubCategories']);

控制器

public function searchSubCategories(Request $request, $id)
{
    $keyword = $request->get('q');

    $subCategories = SubCategory::with('category')
        ->orWhereDoesntHave('category')
        ->OrWhereHas('category', function ($q) use ($id) {
            $q->where('id', $id);
        })
        ->where("subcategory_name", "LIKE", "%$keyword%")
        ->get();

    return response()->json([
        'sub_categories' => $subCategories,
    ]);
}

查看

<div v-show="isFormAssignCategoryMode" class="form-group">
                  <select
                    selected="selected"
                    multiple
                    class="form-control sub_categories"
                    name="sub_categories[]"
                    id="sub_categories"
                  ></select>
                </div>

$('#sub_categories').select2({
 ajax: {
    url: `${BASE_URL}/api/staff/categories/search-sub-categories/` + self.form.id,
    crossDomain: true,
    cors: true,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Origin, Content-Type, Authorization, X-Auth-Token',
    },
   processResults: function (data) {
      console.log(data);
      return {
        results: data.map(function (item) {
          return {
            id: item.id,
            text: item.name,
          };
        }),
      };
    },
  },
});

【问题讨论】:

    标签: laravel vue.js cors jquery-select2


    【解决方案1】:

    这里的问题是您的 Base_URL :8080 中缺少端口,这导致了这个 CORS 错误。

    要解决您需要向您的 VUE 应用添加代理的问题,请检查这将帮助您https://dev.to/alirezahamid/how-to-fix-cors-issue-in-vuejs-545o

    或者,如果您使用的是 Nuxtjs,请查看此软件包 https://www.npmjs.com/package/@nuxtjs/proxy

    另外,我建议您使用vue-select2,以避免在您的 Vue 组件中使用 Jquery 代码

    【讨论】:

    • 我使用 Vue CLI 3,它实际上在 http://localhost:8080 中运行。但是,API 在http://localhost/my-project/laravue/ 中运行。我总是在任何 API 请求中使用这种方式,这很好。只有这种情况我对CORS有问题。我不知道。
    • 浏览器不会让任何来自不同来源的http请求。你在vue.config.js 试过这个吗? module.exports = { devServer: { proxy: 'https://localhost' } }
    • 请注意,您必须将 ajax 调用中的基本 url 更改为 http://localhost:8080
    • 我尝试通过运行php artisan serve 将网址更改为http://localhost:8080。是的,这是工作。 CORS 现在不见了。但是我遇到了一个新问题。我无法获取数据,它显示http://localhost:8000/api/staff/categories/search-sub-categories/?_type=query 404 (Not Found)。我是不是做错了什么?
    • 我假设您仍然没有在 vue.config.js 中正确设置代理因为现在,您仍然从 VUE cli 服务器请求。我认为您必须按照官方文档proxy: { '^/api': { target: 'http://localhost' } }cli.vuejs.org/config/#devserver-proxy中的这个示例来定义所有使用/api/ 的路由才能将您带到Laravel api。
    猜你喜欢
    • 2019-08-05
    • 2021-10-13
    • 1970-01-01
    • 2020-07-14
    • 2020-08-27
    • 2021-02-22
    • 1970-01-01
    • 2018-07-20
    • 2021-10-11
    相关资源
    最近更新 更多