【发布时间】:2016-04-03 12:50:02
【问题描述】:
您好,我是 react 和 Nodejs 的新手。目前,我正在尝试在 react 中创建一个登录组件,其中包含一个按钮,应用程序可以通过该按钮通过 Facebook 对用户进行身份验证。我正在使用 passport.js 进行身份验证。我还使用回流来处理对节点服务器的任何 api 调用。
下面是各自的代码
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;
});
};
当我点击我的应用程序上的 fbLogin 按钮时,我收到以下错误
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.
我想知道使用 fetch 直接将 get 发送到服务器以获取“/auth/facebook”并让服务器处理请求并返回用户对象是正确的方法。如果是,那么这是哪里出错了?如果不是,那么使用 react 实现相同目标的正确方法是什么?
【问题讨论】:
-
我没有看到您的护照配置,但我猜您会在 facebook 上注册一些域(例如 www.mysample.com),并且您的回调 url 在同一个域中。但是,由于您对此进行了测试,因此请求来自不是注册域的 localhost。尝试将主机文件(Mac 上的 /etc/host)设置为指向本地环回地址的域:
code127.0.0.1 www.mysample.com -
问题解决了吗?
标签: node.js reactjs facebook passport.js