首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Azure移动服务服务到服务通信

Azure移动服务服务到服务通信
EN

Stack Overflow用户
提问于 2014-10-16 21:52:49
回答 1查看 76关注 0票数 1

有没有一种方法可以通过内部url从同一移动服务的表拦截器脚本中调用自定义api脚本?

还是您总是必须使用公共url(https://.azure-mobile.net)。在这种情况下,加上X主标头,因为它是服务于服务通信。自定义api只应从此脚本调用,而不应由外部应用程序或经过身份验证的用户调用。我希望防止主密钥甚至通过加密的通道离开服务器。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-17 18:14:34

如果您在不同的服务中,那么您需要使用公共URL,并将您想要调用的API标记为"Admin“访问。

如果您希望从同一服务中的表脚本中调用自定义API,则只需“要求”自定义API并将其作为常规JS函数调用。注意,尽管API接受“请求”和“响应”参数,但这是JavaScript,所以任何看起来像请求/响应的东西都可以工作(鸭子类型)。例如,如果我将这个名为“计算器”的自定义API定义为:

代码语言:javascript
复制
exports.post = function(request, response) {
    var x = request.body.x || request.param('x');
    var y = request.body.y || request.param('y');
    var op = request.body.op || request.body.operation || request.param('op');
    calculateAndReturn(x, y, op, response);
};

exports.get = function(request, response) {
    var x = request.param('x');
    var y = request.param('y');
    var op = request.param('op') || request.param('operator');
    calculateAndReturn(x, y, op);
};

function calculateAndReturn(x, y, operator, response) {
    var result = calculate(x, y, operator);
    if (typeof result === 'undefined') {
        response.send(400, { error: 'Invalid or missing parameters' });
    } else {
        response.send(statusCodes.OK, { result : result });
    }
}

function calculate(x, y, operator) {
    var undef = {}.a;

    if (_isUndefined(x) || _isUndefined(y) || _isUndefined(operator)) {
        return undef;
    }

    switch (operator) {
        case '+':
        case 'add':
            return x + y;
        case '-':
        case 'sub':
            return x - y;
        case '*':
        case 'mul':
            return x * y;
        case '/':
        case 'div':
            return x / y;
    }

    return undef;
}

function _isUndefined(x) {
    return typeof x === 'undefined';
}

注意,对于POST操作,它只需要来自请求的一个'body‘参数,其中包含三个成员(x、y、op),并且响应中唯一的函数是send。我们可以通过将所需的内容传递给计算器,从表脚本中调用它:

代码语言:javascript
复制
function insert(item, user, request) {
    var calculator = require('../api/calculator');
    var quantity = item.quantity;
    var unitPrice = item.unitPrice;
    calculator.post({ body: { x: quantity, y: unitPrice, op: '*' } }, {
        send: function(status, body) {
            if (status === statusCodes.OK) {
                item.totalPrice = body.result;
                request.execute();
            } else {
                request.respond(status, body);
            }
        }
    });
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26414544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档