我正在构建一个小型 Node/React 应用程序,我正在尝试实现 OAuth2 Google 以请求 Google Analytics API。我正在使用 Passport.js来处理认证。
我能够正确获取 token :
router.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/error", session: false }),
function(req, res) {
var token = req.user.token;
res.redirect("http://localhost:5000/?token=" + token);
}
);
但是,在尝试调用 Google Analytics 管理 API 时出现以下错误 Error: Login Required
。
router.get('/getData', function(req, res) {
googleAccounts.management.profiles.list(
{
accountId: '~all',
webPropertyId: '~all'
},
(err, data) => {
if (err) {
console.error('Error: ' + err)
res.send('An error occurred')
} else if (data) {
Console.log(data)
}
}
)
})
如何登录?我缺少哪一步?
最佳答案
您不会发送访问 token ,除非您使用 gapi 的内置身份验证,否则您必须在 HTTP 授权 header 中手动发送访问 token 。
请使用以下代码片段来实现相同的目的。
function listViews() {
gapi.client.setToken{
access_token: <access-token>
})
... rest of the function
关于node.js - “需要登录”错误。使用 Google API 获取 oauth2 token 后如何登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58018756/