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 to remove an event listener when e.target points to a hyperlink

element, I encountered an issue using a slideshow component sourced from our components library. This component receives swipe events from a utility function that is initialized upon mounting. The problem arose while testing on a mobile phone - tapping a ...

Tips for properly removing a key from a .json file using Python

I am working on a discord bot and I need to remove the key (channel id) and value (message id) from a .json file, but I am encountering an error: Ignoring exception in on_raw_reaction_add Traceback (most recent call last): File "C:\Users\b ...

Show a loading icon as the synchronous Ajax request is being sent

Seeking a way to show a spinner while making a synchronous Ajax request to fetch data from the server. Acknowledging that asynchronous mode is preferred, but not permitted in this case. Aware that a sync ajax request can cause browser blocking. An attemp ...

The error message "ReferenceError: express is not defined" indicates that Node.js is

Recently, I started using Nodejs to develop web servers, utilizing the express module. To install it, I used the command: "sudo npm install -g express". However, upon running the program, an error occurred: "ReferenceError: express is not defined ...

problems with hovering over radio buttons in Internet Explorer 9

Encountering a curious issue in IE9: When hovering over my top level wrapper div, the first radio button seems to be triggered as though it's being hovered over. This means that even if the last radio input is selected, clicking anywhere within the wr ...

How to resolve the issue of "Fixing 'Unhandled Runtime Error TypeError: event is undefined'"

Today I encountered this error: Unhandled Runtime Error TypeError: event is undefined and couldn't find a solution online Here's the code snippet: import { ethers } from 'ethers' import { create as ipfsHttpClient } from 'ipfs-h ...

On IOS, Three.js ensures that the RGB values of a texture are set to zero whenever the ALPHA value

Working on a WebGL project utilizing javascript and the three.js framework, I am in the process of crafting a custom shader with GLSL. In this shader, I must load various lookup tables to utilize individual RGBA values for calculations rather than renderin ...

The Implementation of Comet Programming

I'm interested in creating a web application similar to Google Docs where multiple users can edit and view changes in real-time. Would Comet Programming be the best approach for this? As a newcomer to Web Development, I'm currently learning Java ...

Encountering a series of frustrating 404 errors when attempting to submit a React form multiple times

I've been working on developing a new forum using Express and React, but I'm facing challenges with saving form data to the database. Currently, my goal is to store topic titles in a MongoDB collection, with plans to expand to include message con ...

Upon registration, the user's information is successfully stored in the mongoDB database, even if the selected "username" is already in

I am currently working on a web application using the MERN stack. When registering a user with an existing email either through Postman or the front-end form, the user is not added to the database. The same logic is applied to check if the chosen username ...

What is the method used for defining an element within an array in JavaScript?

As I am new to JavaScript, I find myself trying to organize callbacks within an array. An example of what I have been working on: items = [ "test" = async message => { let userCoins = editCurrency('fetch', message.guild. ...

Vue caution: The reference to property or method "list" during render is not defined on the instance. Ensure that this property is reactive and properly declared

I'm currently exploring the characters from the Rick & Morty series app using vue.js, and I am still learning how to use vue.js. However, I encountered the following error and would appreciate help in resolving it: Error1: [Vue warn]: Property or me ...

Struggling to retrieve JSON information from the database using AJAX

I am facing a challenge when it comes to fetching data from my database using these technologies. Here is the current scenario: var username = $('#username').val(); var password = $('#password').val(); // This IP is just an example fo ...

Unable to interpret the JSON reply from the server

I am currently developing a web application that sends data to a website, which then updates its database and returns a JSON array to replace my web app page. I am using AJAX for this query, but I am facing an issue with preventing the overwriting of my we ...

Click the "Login" button using Jquery to gain access

Whenever I hit the Login button, a 500 Internal server error pops up in the console. Can someone guide me on the correct way to perform a POST request using jQuery? I would really appreciate any help. <button class="login100-form-btn" type=& ...

Tips for displaying bar chart labels effectively with ChartJS

I am working on an Angular project and I would like to incorporate a barchart using ChartJS. The data for this chart can vary in size, sometimes being very large. One issue I have encountered is that when the number of data points is large, the labels ove ...

Questions regarding prototype-based programming in Javascript

I am interested in achieving the following using Javascript: function A(){ this.B = function() { ... }; this.C = function() { <<I need to call B() here>> } ; }; I came across a method of method overloading, but I am curious to know ...

Utilizing C# getter property for iterative deserialization

internal class Program { private static void Main(string[] args) { var sourceJson2 = "{\"bizType\":\"123\",\"data\":\"JzLw2uiQT4IzERg7hdGWFaPAilWJy7e4462Gd9VQ0Mbj0qZI3uDe6wWaSklECHjalCTEt/L1ZAyhf/fxocABc8 ...

Steps for adding a forked version of a library in package.json

Recently, I came across a React JS library called React Pacomo. Since the original version of this library is no longer being maintained, I decided to use my own forked version for my project. However, I am facing issues with compiling or building the libr ...

Having trouble locating the module while importing MP3 files in a React project

UPDATE The issue stemmed from my limited understanding of the environment I was working in, but the responses provided below may be helpful for others facing similar challenges. EDIT: It appears that there is a problem with trying to import an mp3 file in ...