Hello I am new to react and Nodejs. Currently I am trying to make a login component in react which contains a button through which app can authenticate the user through Facebook. I am using passport.js for authentication. I am also using reflux for handling any api call to node server.
Below is the respective code for each
actions.js
var Reflux = require('reflux');
module.exports = Reflux.createActions([
"facebookLogin"
]);
store.js
var Reflux = require('reflux');
var Actions = require('../actions');
var Api = require('../utils/api');
module.exports = Reflux.createStore({
listenables: [Actions],
facebookLogin: function(email) {
Api.FBrequest(email)
.then(function(response){
console.log('returned user for facebook from server : ' + response);
}.bind(this));
}
});
api.js
module.exports = {
FBrequest: function() {
return (
fetch('/auth/facebook', {
method: 'get'
}).then(function(response){
return response.json();
})
);
}
};
facebook.js
// file at server for handling passport authentication calls
module.exports = function(app, passport){
// call to facebook for authenticating user
// in response to this call, facebook will reply in /auth/facebook/callback with the user object
app.get('/auth/facebook', passport.authenticate('facebook', {scope:'email'}));
// TODO return error on failure of login instead of navigating to the login route
app.get('/auth/facebook/callback', passport.authenticate('facebook',
{failureRedirect: '/login'}), function(req, res){
// user successfully authenticated by facebook
// return the user object
return req.user;
});
};
When I click the fbLogin button on my app I get the following error
Fetch API cannot load https://www.facebook.com/v2.2/dialog/oauth?response_type=code&redirect_uri=…3A3000%2Fauth%2Ffacebook%2Fcallback&scope=email&client_id=1807765906116990. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I want to know that is it correct approach to use fetch for directly sending the get to server for '/auth/facebook' and let the server handle the request and return with user object. If it is then where this is going wrong ? If it is not then what is the correct approach for achieving the same with react?
For anyone else who stumbles upon this question like I did tonight - we solved this error by having the login button wrapped in an a href tag - which then takes the user to our authorization route. Once the user is authorized, facebook then returns the user to us. Then, every time our component mounts, we make sure the state has our logged in user mounted. If it doesn't we make a get request via axios to a route which passes back the user object, and we set our state appropriately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With