【发布时间】:2017-09-14 02:12:51
【问题描述】:
我想要完成的是使用护照通过 ajax 进行用户身份验证。使用护照的推荐方式是通过GET 请求触发授权过程,该请求使用常规<a> 标签触发。成功(或失败)身份验证后,将重定向到新页面。现在不是使用 html 链接来触发我想通过 ajax 执行的路由。这里的问题是,当我使用第三方身份验证策略(例如 passport-facebook)尝试此操作时,出现 CORS 错误:
XMLHttpRequest cannot load [the facebook auth URL]' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.
这里是相关的服务器端代码:
// route for facebook authentication and login
app.get('/auth/facebook', passport.authenticate('facebook', { scope : ['email'] }));
// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback', (req, res, next) => {
passport.authenticate('facebook', (err, user, info) => {
req.login(user, function(err) {
if(err) return next(err);
return res.status(200).json({
success: "All good man!"
});
})
})(req, res, next);
});
在浏览器中我只是这样做:
axios.get('/auth/facebook').then((response) => {
console.log(response);
});
我发现several 与questions 相似,但似乎都没有一个令人满意的答案。有没有办法真正做到这一点?还是聪明的解决方法?即使路由是使用 html 链接触发的,也许仍然可以发回 JSON 响应?
【问题讨论】:
标签: node.js ajax express passport.js passport-facebook