Using Angular with a hapi.js server that supports JSONP data requests

In my project, there is an endpoint specifically set at /api/profile that accepts post parameters.

var http = require('http');
var serverConfig = require('../server.config.js');
var request = require('request');


module.exports = function(server){
  server.route({
      method: 'POST',
      path: '/api/profile',
      handler: getProfileData
  });


    function getProfileData(request, reply){
        var battleTag = request.payload.battleTag;
        getProfileDataHttp(battleTag, function(err, data){
            if(err){
                reply(new Error(err));
            }
            reply(data);
        });
    }

    function getProfileDataHttp(battleTag, callback){
        var key = serverConfig.battleNet.apiKey;
        var tag =  encodeURIComponent(battleTag);
        var url = 'https://eu.api.battle.net/d3/profile/'+ tag + '/?locale=en_GB&callback=JSON_CALLBACK&apikey=' + key;
        console.log(url);
        request(url,function(error, response, body){
            if(error){
                callback(err);
            }

            if(!error && response.statusCode ==200){
                callback(null, body);
            }
        });
    }
};

Whenever the API is called with a JSON callback, the data returned is in the format:

JSON_CALLBACK({ json data here})

I am trying to figure out how to make this endpoint return only the JSON data. I attempted to use JSON.parse() but it led to errors on the server.

The Angular service responsible for calling this endpoint looks like this:

 function getProfileData(battleTag){
            var defer = $q.defer();

            var tag = validTag(battleTag);
            if(!tag){
                defer.reject('Invalid Tag please use format 1[a-z]11[a-z0-9]#4[0-9]');  
                return defer.promise;             
            }

            $http.post('/api/profile', {
                    battleTag: battleTag
                })
               .success(function(data){
                    if(data.reason){
                        defer.resolve(data.reason);
                    }
                    defer.resolve(data);               
                })
                .error(function(err){
                    defer.reject(err);
                });

            return defer.promise;
        }

Although the call worked when using $http.jsonp in Angular, I had to create the server to hide the secret key from the client.

Answer №1

It appears that there is some confusion in your question regarding JSONP and fetching data directly.

JSONP is specifically designed to encapsulate data inside a function of your choosing for easy execution.

If you prefer to access the data directly without using JSONP, opt for a standard API call instead.

Based on a brief examination of the Battle.net API, it seems that omitting the 'callback' parameter from your request URL will allow you to retrieve the data directly.

In this case, your request URL should resemble this:

var url = 'https://eu.api.battle.net/d3/profile/'+ tag + '/?locale=en_GB&apikey=' + key;

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

Using the methods res.render() and res.redirect() in Express.js

I'm facing a challenge with a route in my express app, where I need to achieve the following: Retrieve data from an external source (successful) Show an HTML page with socket.io listening for messages (successful) Conduct lengthy calculations Send a ...

Interacting with local data using Express server

I am currently in the process of developing a web application for my web art class using Node.js with npm and Express. The concept behind the site is to have the entire body colored in one solid color, but allow users to text a hexcode/CSS color to a Twili ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

How can you make a button in Vue only visible after all API calls have successfully retrieved the data?

Is there a way to make the report button visible only after all the data has been loaded from the latest click of the budget button? Currently, when the budget button is clicked, it retrieves budgets and displays them in a Vue grid using Kendo Grid. To spe ...

Multi-line input in ExtJs

Is there a way to create a multiline input with vertical scrollbars in EXTJS? I tried the following code: noteField = new Ext.form.TextField({ emptyText: 'note...', multiline: true, applyTo: &apos ...

Tips for properly handling special characters in DOM elements

I'm encountering an issue while trying to set CSS based on a condition inside quotes. This is causing a syntax error for me. Can anyone provide assistance in finding a solution? <div> <span ng-class='{\' rdng-error-rate&bsol ...

What are some strategies I can implement to effectively manage different errors and ensure the app does not crash

I came across a variety of solutions for error handling. The key concept revolves around this explanation: https://angular.io/api/core/ErrorHandler Attempts were made to implement it in order to capture TypeError, however, the outcome was not successful: ...

Using Javascript to place a form inside a table

When attempting to add a Form inside a Table, only the input tags are being inserted without the form tag itself. $(function () { var table = document.getElementById("transport"); var row = table.insertRow(0); var cell1 = row.insertCell(0); ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...

An issue arose when attempting to access a Mashape web service with JavaScript

I am attempting to make use of a Mashape API with the help of AJAX and JavaScript. Within my HTML, I have a text area along with a button: <div> <textarea id="message" placeholder="Message"> </textarea> <br><br> ...

Utilize AxiosAbstraction to transmit a Patch request from a Vue.js application to a PHP backend

I need help with sending a PATCH request to update the birthdate of a user (promotor) from Vue.js frontend to PHP backend. The issue I'm facing is that the new date of birth is not getting saved in the database, and the existing date of birth in the d ...

StringContractResolver for generating custom JSON schemas

Is there a way to adjust the JSonSchemaGenerator in order to create a schema from a custom object where string properties are classified as Type String instead of String|Null? Essentially, I want to serialize the Jsonschema without the Null option. For e ...

Find the total of values in an array that may be null or undefined

In this scenario, I have an array that looks like this: myData = [[2, null, null, 12, 2], [0, 0, 10, 1, null], undefined]; The goal is to calculate the sum of each sub-array, resulting in an array like this: result = [16, 11, 0]. The ...

Updating Google Sheets Row by Row with Python and Gspread Library

I’m currently using Python along with gspread in order to input and update data in my Google spreadsheet. After experimenting with two different scripts, I encountered some challenges. The first script resulted in an error stating that the object is not ...

Angular debounce on checkboxes allows you to prevent multiple rapid changes from

Managing multiple checkboxes to filter a dataset can be tricky. I am looking for a way to debounce the checkbox selection so that the filter is only triggered after a certain period of time, like waiting 500ms to a second after the last checkbox has been c ...

Integrating XML API Requests Using HTML and JavaScript

When there is only one item in the XML document, I want to update my inner HTML with the result of an API call. I have managed to successfully make the API call work when there are multiple items in the XML document (thanks to W3). <!DOCTYPE html> ...

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...

Tips for saving data after reading lines in Node.js

I am working on a project where I need to read data from an external text file into my function. How can I efficiently store each line of the file as a separate variable? const fs = require("fs"); const readline = require("readline"); const firstVariable ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...