有没有一种方法可以通过内部url从同一移动服务的表拦截器脚本中调用自定义api脚本?
还是您总是必须使用公共url(https://.azure-mobile.net)。在这种情况下,加上X主标头,因为它是服务于服务通信。自定义api只应从此脚本调用,而不应由外部应用程序或经过身份验证的用户调用。我希望防止主密钥甚至通过加密的通道离开服务器。
发布于 2014-10-17 18:14:34
如果您在不同的服务中,那么您需要使用公共URL,并将您想要调用的API标记为"Admin“访问。
如果您希望从同一服务中的表脚本中调用自定义API,则只需“要求”自定义API并将其作为常规JS函数调用。注意,尽管API接受“请求”和“响应”参数,但这是JavaScript,所以任何看起来像请求/响应的东西都可以工作(鸭子类型)。例如,如果我将这个名为“计算器”的自定义API定义为:
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。我们可以通过将所需的内容传递给计算器,从表脚本中调用它:
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);
}
}
});
}https://stackoverflow.com/questions/26414544
复制相似问题