我尝试使用Nodejs从OAuth2获取扩展用户访问令牌 实际上,程序发送一条消息(在浏览器上):
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?redirect_uri=http%3A%2F%2Flocalhost%3…2Fcallback&scope=user_about_me%2Cpublish_actions&client_id=487932668044758. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
使用标准快速生成器,我修改了index.js中的代码,如下所示:
var express = require('express');
var request = require('request');
var OAuth2 = require('oauth').OAuth2;
var router = express.Router();
var oauth2 = new OAuth2("487932668044758",
"0793918b3ab637b2096787e10643980a",
"", "https://www.facebook.com/dialog/oauth",
"https://graph.facebook.com/oauth/access_token",
null);
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', {
// title: 'Express'
});
});
router.post('/userToken', function(req, res) {
if (!req.body) {
return
res.sendStatus(400)
}
var uid = req.body.uid;
var token = req.body.token;
validate_uid_token(uid, token, res);
console.log('req:', req.body);
console.log("uid: ", uid);
console.log('token: ', token);
// res.send("okie");
});
router.get("/callback", function(req, res) {
console.log('here..form callback');
res.header('Access-Control-Allow-Origin', 'http://localhost3000');
res.header('Access-Control-Allow-Origin', 'https://www.facebook.com/dialog/oauth');
res.header('Access-Control-Allow-Origin', 'https://graph.facebook.com/oauth/access_token');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if (req.error_reason) {
res.send(req.error_reason);
}
if (req.query.code) {
var loginCode = req.query.code;
var redirect_uri = "/"; // Path_To_Be_Redirected_to_After_Verification
// For eg. "/facebook/callback"
oauth2.getOAuthAccessToken(loginCode, {
grant_type: 'authorization_code',
redirect_uri: redirect_uri
},
function(err, accessToken, refreshToken, params) {
if (err) {
console.error(err);
res.send(err);
return;
}
var access_token = accessToken;
console.log('access_token : ', access_token);
// var expires = params.expires;
// console.log('expires : ', expires);
req.session.access_token = access_token;
// req.session.expires = expires;
}
);
}
// res.send('okie');
});
function validate_uid_token(uid, token, res) {
var redirect_uri = "http://localhost:3000" + "/callback";
// For eg. "http://localhost:3000/facebook/callback"
var params = {
'redirect_uri': redirect_uri,
'scope': 'user_about_me,publish_actions'
};
res.redirect(oauth2.getAuthorizeUrl(params));
}
module.exports = router;
点击错误信息中的网址。浏览器抛出ma JSON消息为
{"statusCode":400,"data":"{\"error\":{\"message\":\"redirect_uri isn't an absolute URI. Check RFC 3986.\",\"type\":\"OAuthException\",\"code\":191}}"}
请有人帮助我...非常感谢..