我正在尝试创建一个Azure EasyAPI,以便从我的应用程序中的标识提供者(Microsoft)获取一些用户信息。但是,我从我在网上找到的所有示例中都得到了错误,我在stackoverflow上找到的所有答案都没有帮助。
错误:
Azure Log:
: Application has thrown an uncaught exception and is terminated:
SyntaxError: Unexpected end of input
at Object.parse (native)
at IncomingMessage.<anonymous> (D:homesitewwwrootnode_modulesazure-mobile-appssrcauthgetIdentity.js:35:55)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:903:12)
at doNTCallback2 (node.js:439:9)
at process._tickCallback (node.js:353:17)
法典:
module.exports = {
"get": function (request, response, next) {
request.azureMobile.user.getIdentity('microsoftaccount').then(function (data) {
var accessToken = data.microsoftaccount.access_token;
var url = 'https://apis.live.net/v5.0/me/?method=GET&access_token=' + accessToken;
var requestCallback = function (err, resp, body) {
if (err || resp.statusCode !== 200) {
console.error('Error sending data to the provider: ', err);
response.send(statusCodes.INTERNAL_SERVER_ERROR, body);
} else {
try {
var userData = JSON.parse(body);
response.send(200, userData);
} catch (ex) {
console.error('Error parsing response from the provider API: ', ex);
response.send(statusCodes.INTERNAL_SERVER_ERROR, ex);
}
}
var req = require('request');
var reqOptions = {
uri: url,
headers: { Accept: "application/json" }
};
req(reqOptions, requestCallback);
};
}).catch(function (error) {
response.status(500).send(JSON.stringify(error));
});
//...
}};
感谢您的帮助。
在适用于 Node.js 的 Azure 移动应用的 API 文档中,它指示 getIdentity
方法接受身份验证提供程序的名称作为参数,并返回一个承诺,该承诺在成功时生成标识信息。
因此,您的代码应如下所示:
module.exports = {
"get": function (req, res, next) {
req.azureMobile.user.getIdentity('microsoftaccount').then(function (data) {
var accessToken = data.microsoftaccount.access_token;
//...
}).catch(function (error) {
res.status(500).send(JSON.stringify(error));
});
}
}
获取用户信息的另一个选项是调用/.auth/me
终结点。
var https = require('https');
module.exports = {
"get": function (request, response, next) {
var token = request.azureMobile.user.token;
var options = {
hostname: '<yourappname>.azurewebsites.net',
port: 443,
path: '/.auth/me',
method: 'GET',
headers: {
'x-zumo-auth': token
}
};
var req = https.request(options, (res) => {
var str = '';
res.on('data', (d) => {
str += d;
});
res.on('end', function () {
console.log(str);
response.status(200).type('application/json').json(str);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
}
}