简体   繁体   中英

Laravel API and Ionic 2 Client: CORS No 'Access-Control-Allow-Origin' header

I created an API with Laravel and I try to use it with an Ionic 2 project

I'm trying to make a GET request to my Laravel API.

When I make my http request to

auth/{prodiver}/callback/{userID}/{accessToken}

I got this error:

Failed to load http://api.url.net/api/auth/facebook/callback/XXXX/MY_TOKEN: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8001' is therefore not allowed access.

My route looks like this:

Route::group(['middleware' => ['guest', 'cors']], function() {
    Route::get('test', function () {
        return response()->json('{dummy.data}', 200);
    });

    Route::get('auth/{prodiver}/callback/{userID}/{accessToken}', 'SocialAuthController@callback')->middleware('cors')->name('social.auth'); // social auth
});

But when I try the same code, with the route test , it works and I got the data...

The "facebook connect" isn't the problem, the success callback is triggered.

Here is the callback() method

public function callback($provider, $userID, $accessToken)
{
    if ($provider == "facebook"){
        $user = $this->createOrGetUser($userID, $accessToken);
        auth()->login($user);
        return response()->json($user, 200);
    }
}

All other http requests works perfectly...

Here is the concerned http request (in Ionic project)

let headers = new Headers(); 
headers.append('Content-Type', 'application/json'); 
let url = this.baseApiUrl+'auth/facebook/callback/' + userID + '/' + accessToken; 
this.http
    .get(url, {headers: headers})
    .map(res => res.json())
    .subscribe(data => {
            console.log(data)
        }, err => {
            this.onError(err);
        }
    );

I don't understand what's going on, anyone has a clue ? I'm totally tired of this error :/

Thanks a lot! :)

First, why do you set cors middleware when defining the second route? It is already set for the whole group.

Second, cors returns a cors error in case you have some error in your code, that's its behaviour.

When an error occurs, the middleware isn't run completely. So when this happens, you won't see the actual result, but will get a CORS error instead.

Try to debug your code to find a bug. Test returns data, it means that this is not the cors who gives the error, it is your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM