jQuery Select2 Blocked By CORS Policy in Laravel Vue

  cors, jquery-select2, laravel, vue.js

I am trying to use jQuery Select2 in Laravel Vue. But I have an error below when I use my base url. But, when I use another API service like https://countriesnow.space/api/v0.1/countries/population/cities, it’s okey, data can be retrieved. What’s wrong? I’ve been trying to solve this problem but nothing is gonna work.

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

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

Controller

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

View

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

Source: Laravel

Leave a Reply