Search code examples
node.jsfacebookpassport.jsnativescriptpassport-facebook

CORS issue on NativeScript Facebook authentication with Node.js and Passport


I've implemented Facebook OAuth on Noje.js via Passport library. The URL that invokes Facebook OAuth /auth/facebook and the Facebook callback URL /auth/facebook/callback are as follows:

loginRouter.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));

loginRouter.get('/auth/facebook/callback', passport.authenticate('facebook', {successRedirect: "/rs/login/me"})); 

I have two front-end applications, one is on the web (Angular2) and the other is on mobile (Nativescript). Firstly, I tried implementing the front-end on Angular2 and made an Ajax call to /auth/facebook, which received no response. Further research have revealed that although I've set the Express.js properties to handle CORS properties like this:

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Access-Control-Allow-Origin');
    next();
});

the response from facebook doesn't have the CORS headers set (stackoverflow link). Therefore the solution I've adapted was simply to use <a href> element which does not check the CORS header on response (solution is here), which made everything run perfectly on Angular2.

But when it comes to NativeScript, I cannot find any way to avoid this CORS problem. I'm using the fetch module to make an Http GET request to Node.js with the URL /auth/facebook like this:

public loginFB() {
    return fetchModule.fetch("http://[MY_SERVER_IP]/auth/facebook", {
        mode: 'no-cors',
        method: 'GET' 
    }).then(handleErrors);
};

Although I've set the request mode to "no-cors", this solution simply doesn't work. I've tried to set the CORS headers again on preflight, either at /auth/facebook and /auth/facebook/callback methods, but still, nothings happening. My HTTP request enters the /auth/facebook method but as far as I observed, neither of the middleware and the callback of /auth/facebook/callback method is invoked. What might be the solution?


Solution

  • I managed to use Facebook GraphAPI by being inspired via https://github.com/AntonioCuevaUrraco/nativescript-facebook-login. By using this approach, I've imported the Facebook GraphAPI for Android and used it that way.