Send JSON data from server to client using Express endpoints

I'm having trouble sending a json file to the client and keep encountering internal errors (500). Can anyone assist me with this issue? Additionally, I am using Handlebars as my view engine.

Within app.js:

[...]
var APIconditions = {};
var APIhourly = {};

function retrieveWeatherData() {
    var data = ['/conditionsWU.json', '/hourlyWU.json'];
    request(data[0], function(err, res, body) {
        if (!err && res.statusCode == 200) {
            APIconditions = JSON.parse(body);
        }
    });
    request(data[1], function(err, res, body) {
        if (!err && res.statusCode == 200) {
            APIhourly = JSON.parse(body);
        }
    });
}
[...]

In index.js:

[...]
router.get('/conditions' , function(req, res, next) {
    res.json(APIconditions);
});

router.get('/hourly' , function(req, res, next) {
    res.json(APIhourly);
});
[...]

As for client.js:

[...]
function retrieveWeather() {
    var APIconditions = 'conditions';
    var APIhourly = 'hourly';

$.getJSON(APIconditions, function (data) {
    [...]
});
$.getJSON(APIhourly, function (data) {
        [...]
    });
[...]

Answer №1

If you want to utilize the APIconditions or APIhourly variables in a different file, make sure to explicitly define their access.

To ensure accessibility from any part of your codebase, consider assigning them to the global scope.

window.APIconditions = {}
window.APIhourly = {}

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

A simple method in JavaScript/TypeScript for converting abbreviations of strings into user-friendly versions for display

Let's say I am receiving data from my backend which can be one of the following: A, B, C, D Although there are actually 20 letters that could be received, and I always know it will be one of these specific letters. For example, I would like to map A ...

The callback function within the Service does not execute just once when utilizing $timeout

Looking to implement a service that functions similarly to this example. Here is the code I have so far: app.service('Poller', function ($q, $http, $timeout) { var notification = {}; notification.poll = function (callback, error) { return $ ...

What are some best practices for utilizing `element.offsetParent` in HTML SVG elements?

I'm currently updating some JavaScript code that relies on the .offsetParent property. The recent changes in the application involve the use of SVG elements, which are causing issues with the JavaScript as mySvgElement.offsetParent always returns unde ...

Why isn't my JavaScript AJAX PHP if statement functioning properly?

I have been struggling with this issue for more than two hours now and cannot seem to find a logical solution. When I remove the If statement highlighted by --> this arrow, the alert() function works perfectly fine. It triggers when I simply use if(true ...

Issue with updating the notification badge on the menu bar

My website features a menu bar with a notification bubble badge created using CSS3. I have also implemented a PHP script to fetch the number of new messages from a MySQL database in my messenger inbox system. My goal is to dynamically update the value di ...

Is it possible to showcase the data from three or more PHP files on a single webpage?

I currently have three PHP files: pie.php, bar.php, and line.php. When each file is run individually, it displays a webpage with a pie chart, bar chart, or line graph respectively. However, running all three files opens up separate webpages for each graph. ...

Incorporating .json files into an HTML template with the help of an HTML form designed for selecting a particular

I am faced with a collection of various .json files that I wish to specify by name on an HTML page (local) form, enabling me to load this data onto a table. This is how my HTML form appears: <form> File: <input type="text" Id="file_name"&g ...

Calling an ajax request to view a JSON pyramid structure

My experience with ajax is limited, so I would appreciate detailed answers. I have a Pyramid application where I need to load information via ajax instead of pre-loading it due to feasibility issues. I want to retrieve the necessary information through a ...

Is it possible for a JSON to only have a key without a corresponding value

Keys and values are defined in the Json format. But what about the example below? { "Kill" } Would you consider this a valid Json format? ...

Unable to update state from a graphql query without refreshing the page using React and GraphQL

Currently, I am working on a component that uses GraphQL and the useQuery hook to fetch data for an authenticated user. My goal is to store the retrieved data in global state. When I log the data from the query, it displays correctly as the authed user, ...

Developing a web API project and Front end application on a single port

In my Visual Studio solution, I have two projects - one for front end (HTML, CSS, and JS) and another for a Web API. They are running on separate ports - the front end on 37056 and the API on 6596. In the JS files, I am targeting the Web API controllers su ...

Component fails to update when state updated using useState()

In my current project, I am facing an issue with a parent (App) and child (MUIDatatable) component setup. The child component is a datatable that requires a columns prop to define the structure of the columns, including a custom render function for one of ...

Troubleshooting a VueJS Problem: Updating $data in the mounted hook

Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

Deleting files with a dedicated function (Dropzone.js)

I need to implement functionality that removes the uploaded file when a 'cancel' button is clicked. Here's how my HTML code looks: <div reqdropzone="reqDropzoneConfig"> <form id="requisitionupload" class="dropzone dz-clickable" ac ...

How can I use jQuery to retrieve the total number of elements in a dropdown list?

I am working with a dropdown list that looks like this: <select id="ddlProjects"> <option value="315">resproject</option> <option value="320" style-"display:inline">newheavn</option> <option value="395" style="di ...

Using ng-model within ng-repeat for data binding in AngularJS

My challenge is to connect a model called 'User' to a series of input fields. Since I don't know the specific fields in advance, I need to write generic code that dynamically sets up the form based on the available fields. <script> ...

Using a node module for Three.js path manipulation

Currently, I am in the process of learning Three.js and have set up a basic project that runs on a node.js server while importing Three.js as a node module. Although my setup is working fine, I find myself a little bit confused about whether this is consi ...

Dynamic - Swap out middleware during execution

Currently in my Express application, I am looking to switch out a middleware during runtime. Specifically, I want to stop using one middleware (X) and start using another middleware (Y). While I have found a simple solution, it seems like no one else is su ...

PHP child categories causing jQuery menu loading issue

Our custom jQuery menu has been functioning perfectly on our OpenCart store. However, we are facing an issue where the 2nd level child categories are not being displayed. It seems that there is an error in the PHP code for both the modified and original me ...

I have exhausted all options trying to filter a 2D array in JavaScript

The 2D array provided is formatted as follows : [[ONE,1],[QUARTER,0.25],[QUARTER,0.25]] The desired output should be : [[ONE,1],[QUARTER,0.5]] An attempt was made using array.IndexOf but did not yield the expected result ONE,1,QUARTER,0.25,QUARTER,0.2 ...