我正在尝试在NodeJS网站中使用Simple-OAuth2登录具有客户端凭证流的用户。
我的route / index.js是这样的:
var express = require('express');
var router = express.Router();
var authHelper = require('../helpers/auth');
router.get('/', async function(req, res, next) {
let parms = { title: 'Home', active: { home: true } };
const accessToken = await authHelper.accessToken;
res.render('index', parms);
});
module.exports = router;
我的auth.js是这样的:
const credentials = {
client: {
id: process.env.APP_ID,
secret: process.env.APP_PASSWORD,
},
auth: {
tokenHost: 'https://login.microsoftonline.com',
authorizePath: "common/oauth2/v2.0/authorize",
tokenPath: "common/oauth2/v2.0/token",
}
};
const oauth2 = require('simple-oauth2').create(credentials);
const tokenConfig = {
username: 'uuuuuu@dddddd.com',
password: 'ppppppp',
scope: process.env.APP_SCOPES,
};
try {
const result = await oauth2.ownerPassword.getToken(tokenConfig);
const accessToken = oauth2.accessToken.create(result);
} catch (error) {
console.log('Access Token Error', error.message);
}
exports.accessToken = accessToken;
当我尝试启动网站时,nodejs向我显示了一个sintax错误:
const result = await oauth2.ownerPassword.getToken(tokenConfig);
^^^^^
SyntaxError: await is only valid in async function
这个错误对我来说意义不大,因为代码是由simple-oauth2提供的。
有人能说明我的实际错误吗?
答案 0 :(得分:0)
那么您必须将代码包装到async
函数中,以便可以在该函数中使用await
关键字。您可以找到更多信息here。
在您的情况下,我会将代码包装到函数中并按如下所示导出该函数:
const credentials = {
client: {
id: process.env.APP_ID,
secret: process.env.APP_PASSWORD,
},
auth: {
tokenHost: 'https://login.microsoftonline.com',
authorizePath: "common/oauth2/v2.0/authorize",
tokenPath: "common/oauth2/v2.0/token",
}
};
const oauth2 = require('simple-oauth2').create(credentials);
const tokenConfig = {
username: 'uuuuuu@dddddd.com',
password: 'ppppppp',
scope: process.env.APP_SCOPES,
};
const getAccessToken = async () => {
try {
const result = await oauth2.ownerPassword.getToken(tokenConfig);
const accessToken = oauth2.accessToken.create(result);
return accessToken;
} catch (error) {
console.log('Access Token Error', error.message);
return null;
}
};
exports.getAccessToken = getAccessToken;
然后您可以像这样使用该功能:
var express = require('express');
var router = express.Router();
var authHelper = require('../helpers/auth');
router.get('/', async function(req, res, next) {
let parms = { title: 'Home', active: { home: true } };
const accessToken = await authHelper.getAccessToken();
res.render('index', parms);
});
module.exports = router;