问题
The problem:
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…lhost%3A8080%2Fapi%2Fauth%2Ffacebook%2Fcallback&client_id=1527429390857121. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
If i click the link in the error i get autenticated and get back the datas in json. If i remove the clientside js router everithing works fine. But i am trying to build a SPA app.
I don't use any specific frontend framework, I use flatiron director router and generate the view with handlebars.
On the clientside:
var facebook = function () {
console.log('GET /auth/facebook');
$.ajax({
url: '/api/auth/facebook',
type: 'get',
dataType: 'jsonp',
cache: false
});
};
// ROUTES ===============================
var routes = {
...
'/auth': {
'/facebook' : facebook,
'/twitter' : twitter,
'/google': google
},
...
};
On the serverside:
// send to facebook to do the authentication
router.get('/auth/facebook', passport.authenticate('facebook'));
// handle the callback after facebook has authenticated the user
router.get('/auth/facebook/callback', function(req, res, next) {
passport.authenticate('facebook', function (err, user, info) {
if (err) return next(err);
if (!user) return res.status(403).json(info);
req.logIn(user, function (err) {
if (err) { return next(err); }
return res.json({user: user, message: info});
});
})(req, res, next);
});
in server.js
...
app.use('/api', router);
...
回答1:
It seems to be a cors issue:
Try the following:
$ npm install cors
then, in your server.js:
var cors = require('cors');
...
app.use(cors());
For more details on cors module: https://www.npmjs.com/package/cors
and on cors and ajax: http://www.bennadel.com/blog/2327-cross-origin-resource-sharing-cors-ajax-requests-between-jquery-and-node-js.htm
回答2:
Try to add it to server:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
来源:https://stackoverflow.com/questions/27505268/passport-facebook-strategy-trigger-route-with-ajax