"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

Tips for managing asynchronous code that invokes other asynchronous code in AngularJs

My factory utilizes indexedDB and a method called getRecipe that relies on this indexed db to fetch data. The issue arises because indexedDB returns its instance in an asynchronous call, and getRecipe is another method that also returns its value asynchro ...

Error encountered during Yarn installation process: The tunneling socket was unable to be established due to a connection refusal on localhost at port 80

I have a Next.js app that needs to be built on our company servers before deployment. We use a proxy, and I've configured yarn to use the proxy as well. yarn config set proxy http://xx.xxx.xx:xxxx yarn config set httpsProxy http://xx.xxx.xx:xxxx yarn ...

Upgrading the entire document's content using jQuery

I am dealing with an ajax response that provides the complete HTML structure of a webpage, as shown below: <!DOCTYPE> <html> <head> <!-- head content --> </head> <body> <!-- body content --> </b ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

Locating terms within two attributes of a MongoDB record

Searching for a word from two properties, 'firstname' and 'lastname', in a document has been challenging. The current code is not providing the expected response when searching through multiple properties. As a beginner in mongo db, I w ...

Implementing a restriction clause while executing a load additional data feature

I'm currently working on implementing a basic load more function for my web page. Right now, the page displays 8 results from the database. When the user scrolls, a load more button appears. Clicking this button triggers an ajax request to another PH ...

Iterate over the JSON data and evaluate the timestamps for comparison

I am attempting to iterate through this JSON data and compare the "start_time" and "end_time" values to ensure that there are no overlaps. However, I am struggling to implement this functionality. While researching, I came across a resource on how to vali ...

What is the best way to bring a module into an Angular project?

I have a project in Angular with an additional module created as an npm package. The structure of the module is as follows: --otherModule --other-module.module.ts --index.ts --package.json index.ts: export { OtherModule } from './other-module ...

Is it possible for me to activate a function on a different component using my header?

Hi there, I'm curious about how Vue routing and the tree structure work together. In my setup, I have a parent router that contains both my router-view and header at the same level. I want to be able to trigger some functions from my header component ...

Ways to display a vertical scrollbar within a select box

I'm currently working with an Angular select box and I'm looking to display a scroll bar if there are more than 5 data entries. <select class="form-control" data-ng-model='projectListData.appVersion' ng-selected ng-options="v.versio ...

Add a new sibling item to Angular-UI-tree

I am trying to add a sibling item to a tree when clicked in angular-ui-tree (https://github.com/angular-ui-tree/angular-ui-tree) Here is an example of what I currently have: <item><input value"item A #1"><button>insert under</button& ...

Having trouble executing a MongoDB query through Mongoose without using a REST API

Dealing with the Express router has been an uphill battle for me. While Mongoose models work seamlessly within routes, I've hit a roadblock when trying to utilize the models in other files without routes. Whenever I attempt to run the file containing ...

Disabling form with customized component in AngularJS

I’ve been trying to find a solution, but I’m stuck on this. I created a custom directive called manyToOneSelect that fetches items from the server, displays them to the user, and allows the user to select one item. It’s working fine, but I can’t fi ...

A guide on detecting overflow in a React functional component

I am in search of a way to determine if a div contains overflowing text and display a "show more" link if it does. While researching, I came across an insightful Stack Overflow answer on checking for overflow in a div. The answer suggests implementing a fu ...

Is it possible to load Angular.js without any references?

In the process of reverse engineering a User Interface that is operational but has a few bugs. Created using HTML, CSS, and JavaScript with data acquired through a REST API. The interface is designed for a Windows environment. While examining the index.ht ...

Adjusting the speed of Flexslider with mousewheel control

I am looking to implement flexslider with mousewheel functionality. Here is an example of how I want it to work: $('#slider').flexslider({ animation: "slide", mousewheel: true, direction: "vertical", ...

Utilizing React.hydrate in conjunction with Vue: A Beginner's Guide

Wondering about a unique scenario here - I have a website built with Vue and now I aim to showcase a library I developed in React. In order to steer clear of server-side rendering (SSR), I can simply wrap ReactDOM.hydrate(ReactApp, document.getElementById( ...

Is it possible to add more data to additional fields in a mongoose document after it has already been loaded?

After loading a document, I want to populate additional fields. In the ecommerce application I'm building, I load my cart on all routes using the following code: app.use(function(req, res, next) { Cart.findOne({session: req.cookies['express:s ...

Is there a way to seamlessly integrate typeahead.js with jquery.validate?

Currently, I have a website built on ASP.NET MVC 5 which utilizes jQuery validation (specifically 'jquery.validate.js' in the MVC project template). My goal is to implement type-ahead functionality using 'typeahead.js' on an input field ...

Transfer a single element or document from one collection in a mongoDB database to another collection within the same database

I'm currently working with the MERN stack and using mongoose to develop a news site project. This site will feature two categories of news: new/recent news that I want to display chronologically, and archived news where older news is stored without be ...