"Obtaining a MEAN response after performing an HTTP GET

I'm currently in the process of setting up a MEAN app, however I've hit a roadblock when it comes to extracting data from a webservice into my application. While returning a basic variable poses no issue, I am unsure how to retrieve the result from the webservice.

The output from the webservice is visible in the terminal console, but not on the frontend (angular). When attempting to return the 'options' variable, it displays in the frontend console, but the webservice result does not. Instead, I receive

$promise: Object, $resolved: false,

I'm constructing this using MEAN.js

Here is what I have thus far

shop.server.route.js

 'use strict';

/**
 * Module dependencies.
 */
var shop = require('../../app/controllers/shop.server.controller.js');


module.exports = function(app) {

    app.route('/shop')
        .get(shop.listProducts);

};

shop.server.controller.js

'use strict';

var http = require('http'),
    errorHandler = require('./errors.server.controller');

/**
 * List of Products
 */
exports.listProducts = function(req, res) {

    var options = {
        host: 'http://api.example.com',
        path: '/products?param1=1&param2=2'
    };



    req = http.get(options, function(res) {
        var body = {};

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            console.log('Got Response' + body );
        });
    });

    req.on('error', function(err) {
        console.log( err.message);
        res.send('error:' + err.message);
    });



};

Answer №1

When working with Angular, async processing and callback digestions are key concepts. This means that your http call will return a promise object which gets resolved when the data arrives.

The recommended approach is to use Angular's $http service. As stated in the documentation:

The $http service is a function that takes a configuration object as a single argument, used to generate an HTTP request. It returns a promise with two $http specific methods: success and error.

Your code should resemble the following (on the Angular side):

var params = {};
params.param1 = 'paramdata';

$http.get('/shop', params).
success(function(data, status, headers, config) {
 // Data will contain the results
}).

error(function(data, status, headers, config) {
  // Error data will be available here
});

Feel free to enhance your understanding by referring to the documentation - $http service

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

Is it possible to refresh AdSense banner when the router changes?

Is there a way to reload the AdSense banner ads when the router changes? I've been encountering issues trying to re-add the script and HTML properly. Any guidance on how this should be done would be greatly appreciated... This is just a test for one ...

The function Jquery .stop does not exist

I am encountering an issue with the magicline.stop function while attempting to implement an underline sliding effect for my navbar. I have tried to troubleshoot the problem but have been unsuccessful so far. Below is the code snippet: <nav class=" ...

Tips on displaying a selected choice | Utilizing Material UI Autocomplete

I have successfully fetched data from an API and used it as options in Material UI Autocomplete. However, when I select an option and send it back to the API using a POST request, the selected category is displayed as a number (0) instead of text, as shown ...

What is the method to retrieve a randomly generated class from an id?

Is there a way to target elements that have the class "my_class" within the element with the id of "info_id"? It's important to note that these elements may also have another class, which I'm not interested in selecting. <div id="info_id"> ...

Variability in the values returned by the useState hook

Currently, I am working on developing my initial user signup form, and I have encountered a challenge that seems relatively simple to resolve but goes beyond my current expertise. The issue pertains to the helperText for an MUI select component which is no ...

Error encountered while making an http get request for a node that returns JSON

I've been struggling with this issue for quite some time now. While I've come across similar problems on Stack Overflow, none of the suggested solutions seem to work for me. I keep encountering the following error message: undefined:1 SyntaxErro ...

Gather information from a customizable Bootstrap table and store it in an array

Currently, I have a bootstrap table configured with react-bootstrap-table-next, enabling users to edit cells and input their desired values. After completing the editing process, individuals can click on the "Submit" button to save the table values, which ...

What is the proper way to implement a $scope.$watch for a two-dimensional array in AngularJS?

Having trouble implementing an Angular watch on a multidimensional array I've got a screen where users can see two teams (outer array) with team sheets (inner array) for each team. They can drag and drop players to change the batting order. The batt ...

When I attempt to submit a form using react hooks form to send an email, I keep encountering a CORS error related to Access-Control-Allow-Origin, despite having already addressed it

When I try to submit a form using react hooks form in order to send an email, I encounter the following CORS error. I have already set up corsOptions and passed it to app.use(cors()) Can someone please guide me on how to resolve this issue? //error: Access ...

create a JavaScript array variable for posting items

My goal is to use this javascript to make four posts for the 'var msg' array. However, it currently posts 'encodeURIComponent(msg[i])' four times instead. How can I resolve this issue? var msg = ['one', 'two& ...

The controller element in AngularJS becomes undefined when invoked within a directive

Presented below is a snippet of my controller: myApp.controller('WizardController', function ($scope, $http) { $scope.user = { addressline1: null, cobuyer: null, validate: null, cobuyerfirstname: null, cobuyerlastname: null, ...

What is the best way to resume a paused animation using JavaScript?

My first game involves triggering an animation that transitions the game screen to greyscale when the character dies. Despite my efforts, I have been unable to successfully trigger this animation using document.getElementById("object").animationP ...

In search of an effective solution for effortlessly executing Protractor automations on autopilot

As a quality assurance professional, I develop my automation scripts using Protractor, which is perfectly suited for working with AngularJS. Currently, I manually execute the automation tests by simply clicking "Run" in the software. However, I am interest ...

Struggling with overlaying Bootstrap modals on top of each other

This idea is inspired by the topic Multiple modals overlay I am working on developing a folder modal that allows users to either 1) open an existing file or 2) create a new file within each folder modal. To see how it functions, please run the code below ...

The color of the background does not remain changed permanently

I'm having an issue where the background color changes when I click a button, but reverts back almost immediately to its original color. How can I ensure that the new color stays permanently? Here is a simple JavaScript function you can use: functio ...

Running PHP database commands within JavaScript

My issue involves a list that can have one or more tasks attached to it. Here's how the process works: When a user attempts to delete the list, a PHP code checks the 'tasks' table in MySQL to see if any tasks are linked to the list being d ...

Exploring techniques to maintain search functionality on altered display columns in DataTables.js

How can I ensure that the search functionality works properly on the modified render column in DataTables.js? In the code snippet provided below, my attempts to search data within the render columns are not yielding any results. $('#release-table& ...

Is there a way to update the button's value upon clicking it?

I've hit a roadblock in my tic tac toe game project during class, and I've been struggling for the past two days to get the X's and O's to show up. The deadline for this assignment is tomorrow! Here are the task requirements: COMPSCI20 ...

What are the potential drawbacks of combining the useState hook with Context API in React.js?

Within my code, I establish a context and a provider in the following manner. Utilizing useState() within the provider enables me to manage state while also implementing functions passed as an object to easily destructure elements needed in child component ...

angular.js:13920 Alert: [ngRepeat:dupes] Multiple occurrences in a repeater

I encountered an issue while attempting to parse a JSON file and map it in HTML. Here is the JavaScript code snippet: searhController.orderlogs.results = JSON.stringify(response.data); This is how it's implemented in Angular: <tr ng-hide="searh ...