Utilizing the OrientDB HTTP API within an Angular platform - a comprehensive guide

When trying to query OrientDB from an Angular service method, authentication-related errors are encountered. It appears that two GET requests are required for successful querying of OrientDB.

  1. An Authentication call: Requesting
    http://localhost:2480/connect/<dbname>
    with an Authentication header
  2. The Actual Query: Sending a request to
    http://localhost:2480/query/<dbname>/sql/<query_text>

Error messages observed in the browser console:

  1. XMLHttpRequest error when loading http://localhost:2480/connect/atudb. The preflight request's response does not pass the access control check due to the absence of the 'Access-Control-Allow-Origin' header on the requested resource. Access from origin 'http://localhost:8080' is denied.
  2. GET error at http://localhost:2480/query/atudb/sql/select%20@rid%20as%20rid,%20runOfDay%20from%20TestResult%20where%20executorPlatformData.machineName='niteshk'401 (Unauthorized)
  3. XMLHttpRequest error when accessing http://localhost:2480/query/atudb/sql/select%20@rid%20as%20rid,%20runOfDay%20from%20TestResult%20where%20executorPlatformData.machineName='niteshk'. The 'Access-Control-Allow-Origin' header is missing on the requested resource, leading to denial of access from 'http://localhost:8080'. HTTP status code 401 was returned.

The following Angular service code snippet illustrates the issue:

angular.module('ReportApp')
    .factory('orientdbService', ['$http', '$log', '$q', 
        function($http, $log, $q) {
            'use strict';

            var fac = {};

            fac.config = appConfig;

            fac.query = function(sql, callback) {
                $log.log('Query: '+ sql);

                var url = encodeURI(this.config.orientBaseUrl + "query/" + this.config.dbName + "/sql/" + sql);
                $log.log('Request URI: '+ url);

                connectOrientDb()
                    .then($http.get(url)
                        .then(function(response){ //Success
                                callback(response.data);
                            },
                            function(response){ //Failure
                                callback({
                                    responseStatus: response.status,
                                    responseData: response.data 
                                });
                            }));
            }

            fac.fetchCurrentDayReportIdList = function(hostMachineName){
                if(typeof(hostMachineName) === "undefined"){
                    throw { 
                        name:        "Parameter Missing", 
                        level:       "Show Stopper", 
                        message:     "Error detected. This function parameter 'hostMachineName' is mandatory to evaluate return value.", 
                        htmlMessage: "Error detected. This function parameter '<code>hostMachineName</code>' is mandatory to evaluate return value.",
                        toString:    function(){return this.name + ": " + this.message;} 
                    }; 
                }

                var sql = "select @rid as rid, runOfDay from TestResult where executorPlatformData.machineName='" + hostMachineName + "'";

                var defer = $q.defer();
                this.query(sql,
                        function(data){
                            defer.resolve(data);
                        });
                return defer.promise;

            }

            var connectOrientDb = function(){
                var url = encodeURI(appConfig.orientBaseUrl + "connect/" + appConfig.dbName);
                var req ={
                             method: 'GET',
                             url: url,
                             headers: {
                               'Authorization': appConfig.authPayload
                             }
                         };
                $log.log('Request: '+req);
                var defer = $q.defer();
                $http(req).then(
                        function(res){ //Success
                            $log.log('Response: '+res);
                            defer.resolve(res);
                        }, 
                        function(res){ //Failure
                            defer.reject(res);
                        }
                    );
                return defer.promise;
            }

            return fac;

        }
    ]);

An error occurs when calling fetchCurrentDayReportIdList(). Assistance with the code correction or implementation reference would be greatly appreciated.

Note:

The global variable appConfig stores a JSON object in the following format:

    {
        "orientBaseUrl": "http://localhost:2480/",
        "dbName": "atudb",
        "dbUser": "root",
        "authPayload": "cm9vdDphZG1pbg==",
        "dbPassword": "admin",
        "formatDateTime": "yyyy-MM-dd HH:mm:ss"
    }

Answer №1

When editing the appConfig, ensure to insert Basic within the authPayload section.

"authPayload": "Basic cm9vdDphZG1pbg=="

Additionally, be sure to follow @wolf4ood's advice and enable CORS for proper functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify the h:outputText value dynamically with the power of jQuery!

Is it possible to use jQuery to dynamically change the value of my OutputText component? This is the code snippet for my component: <h:outputText id="txt_pay_days" value="0" binding="#{Attendance_Calculation.txt_pay_days}"/> I would apprecia ...

Enhance the speed of webview on Android devices

I have been working on an application that utilizes a webview to load both HTML and JavaScript files. Unfortunately, I have noticed a significant decrease in performance when displaying the content. Despite trying various solutions such as: webVi ...

Using Bootstrap's nav-pills inside a table

Is there a way to incorporate Bootstrap Nav Pills into a table, with the "tab buttons" located in the last row of the table? I've attempted it but it doesn't seem to be functioning correctly. Check out this link for reference <table clas ...

"Use AJAX to dynamically update a div element when a button is clicked with a specific value

I have a calendar that is being displayed server side using PHP. My goal now is to allow users to scroll through the months with two buttons (<< / >>) without having to reload the entire page. I have come across many similar questions and examp ...

Dynamic Typeahead with Bootstrap - enabling multiple options

Trying to integrate Bootstrap Typeahead into my AngularJS project has presented me with a challenge related to values. I am fetching the data using $http from my Django API server. Currently, I can search for any item and display its name, but what I actua ...

I'm looking for a way to retrieve an object from a select element using AngularJS. Can

I am working with a select HTML element that looks like this: <select required="" ng-model="studentGroup"> <option value="" selected="">--select group--</option> <option value="1">java 15-1</option> <option value="2">ja ...

Updating JavaScript alert title in Android webview: A guide for developers

I have integrated a web view in my Android application, which contains a button. When the button is clicked, it triggers a JavaScript function that displays an alert box with the title "The page at 'file://' says". I would like to customize this ...

Having trouble generating an Xpath that can partially match a CSS selector like `a[href*="https://stackexchange.com/"]`

Looking to extract the Href of Hot Network Questions from Is there an Xpath equivalent to a[href*="https://stackexchange.com/questions?tab=hot"] //a[Href*"https://stackexchange.com/questions?tab=hot"] The code above works well, but... //a[@href='h ...

"Enhance Your Validation Process: Implementing Foundation 6 Custom Abide with

I've been working on creating a unique abide validator that checks if the username already exists. However, most of the information I find online is for foundation 5 and has different structure. Foundation.Abide.defaults.validators['checkUser&ap ...

Electron's start script leads to project failure

Despite extensively searching the internet for a solution, I have yet to find a definitive answer that actually works. My last resort was downloading the example from Electron's website and directly inserting the scripts into my project. However, whe ...

efficiently manage various nested levels of request parameters

I am configuring routes for my express app and need the following paths: /regions /regions/europe /regions/europe/france /regions/europe/france/paris Currently, I have set up individual route handlers for each path. Is there a more efficient way to ha ...

Issue with IE11: the selected list is not displayed when using the <s:optiontransferselect> tag

When moving groups from left to right in the s:optiontransferselect for selectedGrps and unselectedGrps, the SelectedGroups list is showing as null on form submission in IE11. However, in Chrome and Mozilla, it functions correctly. Any advice would be grea ...

Rendering ng-include before setting the source

Is there a way to prevent the ng-include directive from trying to render before a value on scope is set? Consider the following example: <ng-include src="'./lib/templates/' + $parent.currentEditable.editTemplate"></ng-include> It s ...

Utilizing React's multiple states for enhancing click event functionality

Here's the scenario: I am currently developing a Simon-Says game app using React Native. In this game, the user is shown a sequence of flashing buttons and must press them in the correct order. My main concern is figuring out how to utilize two diffe ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...

Issue encountered where Moment locale functionality is working in local development environment, but not functioning properly in the

My application built with Next.js requires displaying the date in Bengali instead of English. The issue arises after running the build command 'build:next build' where the production version displays the date in English (e.g. '20 January, Su ...

There is a syntax error in the for-loop within the AngularJS $http.get causing an unexpected identifier

I'm encountering a 'syntax error: unexpected identifier' and my browser seems to be getting stuck in a loop after executing this code. I figured incorporating setInterval for delaying API requests was a sound strategy according to the API re ...

Best practice for retrieving the $scope object inside the ng-view directive

Check out my plunk. Incorporating ngRoute into my project. I want to increase a value using ng-click, and upon clicking "Show total", the ng-view template should display the updated value. However, it seems like the scope is not being accessed as expecte ...

execute numerous Jssor Caption instances simultaneously

I have a Jssor slider and I want to create an animation for the first slide. My goal is to make two images come from the sides and merge in the center. I tried using a div for each image with a caption, and it works well. However, the second image starts ...

Troubleshooting JavaScript in Internet Explorer 9

Currently, I am encountering an issue while attempting to debug JavaScript .js files in my Solution using Visual Studio 2010 and IE 9. Despite placing breakpoints in the files, I am unable to debug successfully. I have attempted various troubleshooting ste ...