如何验证对AngularJS上的OrientDB函数的HTTP请求? [英] How to authenticate a HTTP request to an OrientDB function on AngularJS?

查看:109
本文介绍了如何验证对AngularJS上的OrientDB函数的HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下OrientDB函数:

I have the following OrientDB function:

http://localhost:2480/function/Application/getPassFailCount/9:600

它返回以下JSON结果:

And it returns the following JSON result:

{"result":[{"@type":"d","@version":0,"pass":16.0,"fail":2.0,"@fieldTypes":"pass=d,fail=d"}]}

我需要做的是获取"pass""fail"的值以在我的网页中使用.

What I need to do is to get the values of "pass" and "fail" to use in my web page.

到目前为止,我已经使用AngularJS完成了此操作:

So far I have done this with AngularJS:

$http.get('http://localhost:2480/function/Application/getPassFailCount/9:600').
success(function(data) {
    $scope.data = data.result;



//    $scope.passCount = ;
//    $scope.failCount = ;

});

当前,它给出错误"401未经授权".如何验证请求?

Currently it gives the error "401 Unauthorized". How do I authenticate the request?

如果可能的话,任何人都可以提供一些有关如何从返回的JSON结果中获取passCountfailCount的提示吗?

And if possible, can anyone give some tips on how to get the passCount and failCount from the JSON result returned?

推荐答案

The OrientDB HTTP API documentation states that you have to use HTTP Basic authentication for issuing commands. That means you have to include an Authorization header along with your request.

有几种方法可以实现此目的,这是一种更简单的方法.使用$http.get的配置对象参数来设置请求的标头:

There are a few ways to achieve this, here is a simpler one. Use the configuration object parameter for $http.get to set the header on the request:

function base64(str) {
    return btoa(unescape(encodeURIComponent(str)));
}

$http.get('http://...', {
    headers: { 'Authorization': 'Basic ' + base64(user + ':' + password) }
}).success(...);

您绝对应该将所有数据库逻辑移至Angular服务,以便可以将此代码放在一个位置,而不会污染控制器.

You should definitely move all your database logic to an Angular service, so you can keep this code in one place instead of polluting your controllers.

要使其更加整洁,您可以查看 $ http拦截器并编写一个请求拦截器,将请求头添加到每个 HTTP调用中.

To make it even cleaner, you could look into $http interceptors and write a request interceptor that adds the header to every HTTP call.

关于JSON问题:您可以看到结果对象包含具有单个元素的数组.使用索引来获取实际记录.

Regarding the JSON question: you can see that the result object contains an array with a single element. Use indexing to get the actual record.

var result = data.result[0];
$scope.passCount = result.pass;
$scope.failCount = result.fail;

如果您像我提到的那样编写了服务,则可以从控制器中隐藏此实现细节.

If you wrote a service as I mentioned, you could hide this implementation detail from your controller.

function getCount() {
    return $http.get(...).then(function (data) {
        var result = data.result[0];

        // the caller will only see this simpler object
        return { pass: result.pass, fail: result.fail };
    });
}

这篇关于如何验证对AngularJS上的OrientDB函数的HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆