Using Sails.js to display JSON data retrieved from an HTTPS request in the view

Just getting the hang of Sails.js, so any help is appreciated.

I've used an XML service and successfully converted it to JSON using xml2js

var req = https.request(options, function(res) {

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

    res.on('end', function () {

        var result = parseString(xml, function (err, result) {
            console.log(JSON.stringify(result)); // Position 1
        });

        return result;
    });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message); 
});

req.write(data);

var result = req.end();

        console.log('Result: ' + JSON.stringify(result)); // Position 2

res.view({ message : 'hello', result : result });

The view is loading fine, and <%= message %> displays hello. Good.

Console.log at Position 1 shows the stringified JSON object - Great.

However, Console.log at Position 2 returns Result: true - Not ideal.

I'm looking for a way to pass that JSON data to my view for further processing. Any suggestions?

Answer №1

It seems like there is a misconception that calling req.end() will automatically provide the response from the initial https.request you made above. However, there are a few mistakes in this assumption:

  1. req.end() is actually used to complete writing to an open request, not to receive a response. As per the documentation, the return value is unspecified.
  2. The https.request function works asynchronously; even if req.end() did work as expected, the response would not have arrived yet by the time you call it.

To rectify this issue, you should place your response code (such as res.view) within the handler for the end event that you've already defined. Additionally, consider renaming your variables for the remote request/response to prevent conflicts with the req and res variables in your controller action. A revised version of your code could look something like:

myAction: function (req, res) {

    // Assuming options are set elsewhere
    var options = {url: 'http://example.com', ...}

    var request = https.request(options, function(response) {
    
        var xml = '';
        response.on('data', function(chunk) {
            xml += chunk;
        });

        response.on('end', function () {

            var result = parseString(xml, function (err, result) {
                return res.view({ message : 'hello', result : JSON.stringify(result)});
            });

        });
    });

    request.on('error', function(e) {
        console.log('problem with request: ' + e.message); 
        res.serverError(e);
    });
}

You may also want to consider using libraries like the Request module to streamline your external requests and avoid handling events such as data and end manually.

Answer №2

Should you require passing json to a JavaScript variable:

let clientJson = <%- JSON.stringify(serverJson)%>

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

How can I display color without using Winston's color formatter in text?

Currently, I am in the process of developing a logging module using winston as the selected logging framework. It offers the convenience of specifying colors, which is particularly appealing when utilizing the Console transport. However, if I were to defin ...

What is the most efficient method for transferring rows from an SQL Database to JavaScript?

Recently, I've been exploring the dynamic features of HTML5 IndexedDB controlled by Javascript and how to sync it with an SQL Server database for offline access. The challenge I'm facing is determining the most efficient method to transfer data ...

Steps to gradually add content to a JSON file

Currently, I am working on a program that involves creating an extremely large json file. The conventional method of using json.dump() to dump a dictionary list has become impractical due to the sheer size of the list exceeding available memory and swap ...

Execute JavaScript code via URL injection

One interesting aspect of the HTML is that it has a feature where it opens a webpage. The specific webpage it opens is determined by the URL, for example: https://mywebsite.com/index.html&audio=disabled In addition to this, there is a useful JavaScri ...

Is my input file in Javascript valid and does it exist? Here's how to check

In my Javascript code, I am retrieving strings from a text file. When the user inputs an incorrect or invalid file name, I want to display a message. For example: console.log("Your input is invalid"); Here is the code snippet that reads the text file and ...

Getting the ng-model value from a Directive's template and passing it to a different HTML file

When working with my name directive, I am unable to retrieve the value of ng-model from the template-url. team-two.html <form name="userForm" novalidate> <div name-directive></div> </form> <pre>{{userForm.firstname}}< ...

Need help resolving the issue of "Type Property '' does not exist on type 'IntrinsicAttributes & Function'? Let's find a solution together

Looking at my parent component below: import FilterComponent from 'filter/filterComponent' const handleReload = useCallback( (event: MouseEvent) => { event.preventDefault(); // implement logic here }, [Reload, Fetch ...

steps to verify the status of a sent request

I am utilizing the contenteditable property in a p tag. My code is as follows: <p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px ">&l ...

Error: The variable "user" has not been declared in server.js when using passportjs

As a novice with limited experience and a tendency to borrow code snippets from various sources, I'm struggling to identify the root cause of the Reference Error: User is not defined. This particular error crops up when I try to input or submit a new ...

"Encountering HTTP 400 Bad Request Error When Using Flask and Ajax for Post Requests

I'm currently developing a small Flask-based website and I want to use Ajax to send data from the client to the server. So far, I've only used Ajax requests to fetch data from the server, but this time I want to submit data via a POST request. O ...

Error: The getter callback for the component `RNCSafeAreaProvider` must be a function, but it is currently undefined

After attempting to update my React Native app's dependencies using npm update, chaos ensued. To rectify the situation, I reverted back to the previous package-lock.json, deleted the node_modules folder, and re-ran npm i. Surprisingly, instead of res ...

Information backed by the HTML5 Local Storage feature

Is it possible to use a Local Storage object to store another Local Storage object? Thank you in advance. ...

The function req.isAuthenticated() always returns false and never evaluates to true

My goal is to create user authentication using the following code: userRouter.post("/login", passport.authenticate("local", { session: false }), (req, res) => { if (req.isAuthenticated()) { const { _id, username } = req.user; const t ...

Choosing multiple images using JavaScript/jQuery

Gridster is being used for a webpage, with widgets containing images that can be added and deleted using the "+" and "X" buttons. Current Status Clicking the "+" button opens a modal where multiple images can be selected and added to the widgets by click ...

What is the method for sorting flowfiles by their contained data?

Within a single output flowfile, there are 23 rows of data, each with a key and value. If any similar flowfiles in the queue do not contain all the necessary rows of data, they should be directed to the unmatched queue. What processor or method would be ...

JavaScript | Calculating total and separate scores by moving one div onto another div

I have a fun project in progress involving HTML and Javascript. It's a virtual zoo where you can drag and drop different animals into their designated cages. As you move the animals, the total count of animals in the zoo updates automatically with the ...

Kendo UI Web - MultiSelect: choosing an option multiple times

Currently, I am encountering an issue with the Kendo UI MultiSelect widget when trying to select an option multiple times. An example of this is shown in the image below where I want to choose Schindler's List again after selecting The Dark Knight. Ho ...

How can I connect the box using the Interactive Picture jQuery tool?

When using the Interactive picture jQuery, I have the following code snippet within my document: jQuery(document).ready(function(){ $( "#iPicture6" ).iPicture({ animation: true, animationBg: "bgblack", animationType: "ltr-slide ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

Utilizing AngularJS scope within a modal viewport

I am encountering an issue with my simple controller while fetching and displaying messages using $http.get in HTML using ng-repeat. The problem arises when trying to access the messages from a modal window, as it always prints the first message only. ind ...