skip to Main Content

Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I’m building an application with Vue (VueX, vue-router, …) and OctoberCMS. I create virtual domain for API and APP in local via MAMP. I had config all CORS via plugin ‘rluders-cors’ in OctoberCMS.

Route::group(
    [
        'prefix' => 'api/v1',
        'middleware' => ['api','jwt.auth','BarryvdhCorsHandleCors'],
    ],
    function () {
         // Routes here
    }
);

When I deployed into VPS (Centos 6), I have above response from browser. I had added header in .htaccess file of API. And when I open API dirrectly via browser (turn of jwt.auth middleware), I get all header which set in .htaccess file. But in App, don’t work.

I tried to use primary domain for App (abc.example) to call the API from my virtual domain in local (local.local), it still worked. But I tried local App to call the primary API in VPS, it didn’t work.

Please help me! Thanks.

2

Answers


  1. So my solution for routes was to look for a preflight response. So in the request data if it is empty I am sending the preflight response (I think any string would do). Then here comes a request that is not empty. This was the easiest work around that I have found. You still have to allow access control domain. I typically set it to all and always have a token system to authenticate methods other than GET.

    Route::match(['POST', 'OPTIONS'],'api/update-todo', function(Request $req) {
    $data = $req->input();
    if (!empty($data)) {
        Todo::where('id', $data['id'])
            ->update([
            'name' => $data['name'],
            'description' => $data['description'],
            'status' => $data['status'] 
        ]);
        return response()->json([
            'Success' => $data,
        ]);
    } else {
        return response()->json([
          'Success' => $req,
        ]);
    }
    });
    
    Login or Signup to reply.
  2. In my case, it worked with :

    Route::options('/{any}', function() {
       $headers = [
            //'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization'
       ];
       return Response::make('You are connected to the API', 200, $headers);
    })->where('any', '.*');
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search