How can I utilize angular's $http service to fetch a JavaScript file?

I've been exploring the integration of Angular with Node.js and attempting to establish a connection to a MySQL database.

Within my script (server.js), I am utilizing the node mysql module as shown below:

var  mysql=require('mysql');

var connection = mysql.createConnection(
        {
            host         : 'localhost',
            user         : 'root',
            password : '',
            database : 'mysql',
        }
);

connection.connect();

var queryString = 'SELECT * FROM users';

connection.query(queryString, function(err, rows, fields) {
    if (err) throw err;

    for (var i in rows) {
        console.log('Post Titles: ', rows[i].post_title);
    }
});

connection.end();

My goal is to execute the js script using Angular in the following manner:

var myApp = angular.module('myApp', []);

myApp.controller('AppListCtrl', ['$scope', '$http',
    function($scope, $http) {
        $http.get('../scripts/server.js').success(function(data) {
            console.dir(data);
        });
    }

However, this approach does not seem to be working as intended since the js file is not being executed. Should I encapsulate my js code within html tags? Am I approaching this problem incorrectly? My preference is to achieve this solely through JavaScript without relying on php or any other programming language.

Answer №1

When you use the $http.get method, it sends an AJAX request to fetch a JavaScript file as a string that can be consumed by your code.

If you are looking to execute any downloaded file as JavaScript, then JSONP is what you need. Consider using $http.jsonp instead.

Check out the Angular documentation on $http.jsonp

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

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

A guide to retrieving data in React with useSWR whenever the state changes

In a specific scenario, I need to be able to choose users from a dropdown menu. Once a user is selected, the app should display that user's data. Upon loading the page, the app fetches the data for the first user in the array allUsers?.[0]: const [us ...

Retrieve the URL of the image from an XML document

Figuring out how to extract the image URL from XML files in Android Studio can be challenging. After analyzing 30 RSS Feed XMLs, I discovered that 95% of them contain ".jpg" images with links starting with "http," not "www." Therefore, I am working on a co ...

Which special characters are restricted in a JSON.parse function?

I have been encountering a parse error repeatedly after receiving my response. Could it be due to the presence of illegal characters? Below is the response data: [{"businessID": ChIJ49DlQ5NiwokRQ_noyKqlchQ,"latitude": 40.733038,"longitude":-73.6840691,"a ...

Assign a value to a text input using React

Whenever the closeEmail function is triggered or called, I need to set the email.emailAddress as the value of the textfield. I'm fairly new to React, what is the syntax or method to achieve this? Any suggestions? #code snippet <div style={{ disp ...

Trouble exporting specific fields in Mongoexport due to issues with the JSON

I have a MASSIVE COLLECTION (146k documents) of Geonames stored in my MongoDB database named db_Name. Below is the schema for reference: https://i.stack.imgur.com/s7EVf.png My goal is to export specific fields to a JSON file: fields.name, fields.countr ...

Exploring the power of VueJs through chaining actions and promises

Within my component, I have two actions set to trigger upon mounting. These actions individually fetch data from the backend and require calling mutations. The issue arises when the second mutation is dependent on the result of the first call. It's cr ...

Tips on adding background images to your chart's background

Is there a way to set an image as the background in Lightning Chart using chartXY.setChartBackground? ...

ExpressJs routing is throwing a "404 Not Found" error when attempting to

I am relatively new to using Express, and I have set up a route for accessing a single record using the ObjectID from MongoDB (/report/:id). However, when I try to open the route, it displays "Cannot get /report/ObjectID". The code in the router file is as ...

The problem is that the code is attempting to use the express.static method to serve static files from a directory called 'public', but it is unable to do so because the '

How to handle console commands in NodeJS? When I try using app.use(express.static(path.join(__dirname, 'public'))); I encounter the error message "ReferenceError: path is not defined" The version of express I am currently using is 3.3.5. Can a ...

Change the z-index of divs when clicked

When a button is clicked, I want to iterate through a group of absolutely positioned children divs with varying z-indexes. The goal is for the z-index of the currently visible div to decrease on each click, creating a looping effect where only one div is v ...

divs adjust their size based on how many are placed in a single row

I'm in the process of developing an online editing tool, and I'm interested to know if it's feasible to adjust the size of a <div> based on the number of visible div elements. For instance, I have a row with three columns, each set at ...

The base64 conversion for the image is overflowing from the upload image field in react-draft-wysiwyg

I have a functional react-draft-wysiwyg editor application that allows me to add images. However, I am currently encountering an issue which is detailed below: https://i.stack.imgur.com/HTjAc.png This is the code snippet of what I have attempted so far. ...

What could be the reason that Ng Repeat fails to work when a button is triggered from a separate form

I have an HTML table that includes an ng repeat directive and two buttons. The first button opens a modal with a form to create a new user. When I click save, it adds the new user to the list. The second button is within the same form and also adds a user. ...

Combining and adding together numerous objects within an array using JavaScript

I'm looking to combine two objects into a single total object and calculate the percentage change between the two values. I'm encountering some difficulties while trying to implement this logic, especially since the data is dynamic and there coul ...

Java - RESTful API endpoint that serves images when available and JSON data when images are not available

I am currently working on incorporating a mobile front-end using the Ionic Framework along with the $cordovaFileTransfer plugin. My focus is on fetching and uploading a person's Profile Photo. Uploading the photo is functioning properly, but I am enco ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

Vue.js: Incorporating a client-side restful router using vue-router and a state manager

Trying to set up a client-side restful api with vue.js and vue-router where route params can be utilized to showcase a subset of a store's data into components. All the necessary data for the client is loaded into the store during initialization (not ...

Utilize Jest to mock an error being thrown and retrieve the specific error message from the catch block

Below is a snippet of code where I am attempting to test the method getParameter for failure. The module A contains the method that needs to be tested. The test is located in Module A.spec. The issue I am facing is that the test always passes, as it never ...

Error encountered while populating mongodb database with nodejs

Currently working on a nodejs, express, mongoose project and attempting to seed the database. MongoDB is activated but when I try to run the following command: $ node product-seeder.js (node:2810) UnhandledPromiseRejectionWarning: Error: Invalid schema, ...