jQuery Select2 在 Laravel Vue 中被 CORS 策略阻止

jQuery Select2 Blocked By CORS Policy in Laravel Vue

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

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,
          };
        }),
      };
    },
  },
});

这里的问题是您的 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 代码