The $http GET request is redirected to the incorrect URL, resulting in the search

Currently, I am in the process of developing a single page application and utilizing Angularjs v1.2.28 for this project. In order to retrieve data from the backend, I have implemented an HTTP GET request using the following code snippet.

return {
        getCategories : function(sessionid,terminalid,tableno,section){

            var req = {
                     method: 'GET',
                     url: Config.url+ "/menucategories",
                     params : {
                         'sessionid' : sessionid,
                         'terminalid' : terminalid, 
                         'tableno' : tableno,
                         'section' : section
                     }
            };

            return $http.get(req);
        },

The controller relies on the promise object returned by the service, as demonstrated below.

var categoryPromise = categoryService.getCategories(sessionid,terminalid,tableno,section);
    categoryPromise.then(function(payload){
        var categories =  payload.data;

        if(categories.status.code == "1"){
            if(Object.prototype.toString.call(categories) === '[object Array]') {
                $scope.categories = categories;
                categoryService.setCategories(categories);
                $scope.pax = tableService.getPax();
                $scope.tablechair = tableService.getChoseTableChair();
            }
        }
        else{
            $location.url("/login");
            $scope.errorMsg = categories.status.desc;
        }
    },function(errorPayload){
        $location.url("/login");
        $scope.errorMsg = "Server error while processing the request.Please contact system administrator";
    });

Despite my efforts, I have encountered an issue where the errorCallback is consistently triggered due to the URL being altered to the browser application URL with additional characters appended. The intended URL provided is as follows:

http://localhost:8080/CafexRestful/menucategories

Nevertheless, it transforms into the browser application URL displayed below:

http://localhost:8080/CafexMobile/[object%20Object]

My attempts at debugging through Chrome and Firebug have been unsuccessful thus far. It seems to be an underlying issue that requires further investigation. Strangely enough, the same code functions seamlessly with another controller and service when fetching different data. Any insights or additional information would be greatly appreciated. Thank you.

Answer №1

Make sure to use a URL string with $http.get. It's important to avoid passing an object as the argument.

Example of using $http.get function:

  return {
            getCategories : function(){

                return $http.get("/menucategories"); // remember to provide a URL string
            },

Alternate method using $http only.

return {
        getCategories : function(sessionid,terminalid,tableno,section){

            var req = {
                     method: 'GET',
                     url: Config.url+ "/menucategories",
                     params : {
                         'sessionid' : sessionid,
                         'terminalid' : terminalid, 
                         'tableno' : tableno,
                         'section' : section
                     }
            };

            return $http(req); // utilize $http function directly
        },

For more information, refer to the documentation: https://docs.angularjs.org/api/ng/service/$http

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

Integrating JQuery with Sencha Touch: A Comprehensive Guide

Can you show me how to use JQuery with Sencha Touch? I have a Sencha button but when I click on it, nothing happens. I've checked that JQuery is working. xtype: 'button', text: 'Get result', docked: 'bottom', id: 'm ...

Tips for adjusting the border color of a MUI Select field

https://i.stack.imgur.com/rQOdg.png This MUI select box changes color from blue to black based on selection. The challenge is to customize the text and border color to white (currently set as blue). Any suggestions on how to achieve this? ...

Tips for preventing $digest cycle already in progress error while testing

I've been struggling to test a service that utilizes the Google Maps Geocoding service. I initially thought it would be simple since the code is pretty straightforward, but it's proving to be more complex than expected. Here's an overview o ...

How to insert an element INTO a JSON array using JavaScript

I'm having an issue with the way a line is displayed on my screen: Would you like to pay €xx to POS_ID Latte X 1....€2.50-Salad X 1....€4.00-Wrap X 1....€4.50-Coffee X 2....€3.00- My desired format is as follows: Would you like to pay ...

Ensure that useEffect is triggered before the render process is finished, or consider using an alternate method to achieve

How can I trigger functions to execute when state changes without waiting for the render cycle to complete and without using up memory with useMemo or useCallback? Is there a way to achieve this similar to useEffect, but more direct and efficient? ...

What steps should I follow to successfully incorporate Zurb Foundation 4 Sections (tabs) into my Javascript Ajax functionality?

I am currently incorporating Zurb Foundation 4.1.5 into my application and I am faced with the challenge of implementing Zurb Section Javascript to handle "tabs" on the page. The content within these tabs is dynamic and fetched via Ajax calls. I am seeking ...

Creating a smooth transition curve for moving the camera along the z-axis using JavaScript and Three.js技

I am venturing into the world of Three.js and facing a challenge. In the center of my scene, I have a rotating icosahedron. When I click a button, it should start rotating faster and the camera should move closer to make it appear larger. However, I am str ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

Encountering an error when using Angular Material virtual scroll in conjunction with Angular-UI

Trying to incorporate Angular material's virtual scroll feature on angular-ui-tree is proving to be a bit challenging. The error message that keeps popping up is: Controller 'uiTree', which is required by directive 'uiTreeNode', ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...

How can the md-sidenav be automatically opened when a specific ui-router state is loaded, without being locked in the open

I am facing an issue with my md-sidenav in certain ui-router states. I need it to be open in some states and closed in others, while also animating the opening and closing transitions between states. Ideally, I would like to have a function that automatica ...

PHP and AJAX concurrent session issue causing difficulties specifically in Chrome browser

TL;DR. I'm encountering an issue in Chrome where different requests are seeing the same value while incrementing a session counter, despite it working fine in Firefox and Internet Explorer. I am attempting to hit a web page multiple times until I rec ...

Retrieving distinct items from an array containing nested objects and sub-properties

In my script, I am attempting to retrieve unique objects based on the state from an array of objects. The current script is functioning correctly for most cases. However, there is one scenario where a nested object in a specific state has a sub-state, and ...

What is a creative way to store and organize ids along with their sub ids in an object without relying on arrays?

Currently, I am faced with the challenge of sending data to the server that contains multiple ids with sub ids. I have been utilizing arrays to handle this, but the repetitive use of find() and findIndex() functions in the DOM (specifically with Vue) is st ...

Accessing controller in Angular directly from the HTML without using $scope

Currently, I am working with the latest version of Angular and have been advised to eliminate the use of the $scope object. As a result, when referencing my controller from the HTML page, I now use an alias: <div ng-controller="MyController as ctrl"&g ...

Mongoose: Enhancing Arrays with maximum values for each item

How to Update an Array Property in Mongoose with Item-Wise Max and Default Null Upon Instantiation I have a MongoDB collection that stores time series data in a fixed-length array (1 item per minute, 1 document per day). { 'series': '#1& ...

Implementing i18n in NextJS with a focus on maximizing SEO performance

My task was to implement internationalization (i18n) for our company website. Currently, we are using Netlify with @netlify/plugin-nextjs, and I encountered an issue when trying to submit a PR. An error popped up stating: Error: i18n support is not compati ...

Vue.js blocks the use of iframes

I've come across a peculiar issue where I need to embed an iframe inside a Vue template and then be able to modify that iframe later. The code snippet below shows the simplified version of the problem: <html> <body> <div id="app" ...

execute a function for every regex match found within a string

When working with WordPress or PHP in general, I came across this interesting recommendation for email obfuscation, and I would like to: Convert email addresses to mailto links Encode the mailto links using str_13() Decode them client-side using JavaScri ...

By employing the $watch method, the table disappears from the div element

I've integrated the isteven-multi-select directive for my multi-select dropdown functionality. By providing it with a list of thingsList, it generates a corresponding checkedList as I make selections. Initially, I used a button to confirm the selecti ...