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

aggregating information from various asynchronous sources in AngularJS and combining them into a single object

As a beginner in AngularJS and the concept of deferred/promises, my code may not be perfect. I have encountered an issue and would appreciate some guidance on what I might be doing wrong. Essentially, in my factory, I am making two asynchronous calls. The ...

Modifying the page's left attribute dynamically with jQuery based on window resize

I am currently facing a small issue with my code. My goal is to update the 'left' CSS property of certain elements based on the difference between their current left value and the page resize amount. This way, when the background moves with a pag ...

Tips for accessing the parent method within a jQuery AJAX success function

Similar Question: javascript how to reference parent element Hello everyone! This is my first time posting here. I have a question - how can I trigger alerts from a successful AJAX call? var page = { alerts: function (json) { if (json ...

Transform a JSON array into a dataframe

I'm encountering an issue with converting a JSON file into a data frame. Despite using the jsonlite library along with the fromJSON() and unlist() functions, I'm struggling to structure the data in the desired format. The JSON file is organized ...

Showing list data from script to template in vue - A step-by-step guide

My task involves displaying data from the main table in MySQL. I need to show the type of each major by comparing it with the id in the faculty table. I have successfully logged this information using console.log, but I'm unsure how to display it on t ...

Determining the positioning of a tablet with a JavaScript algorithm

We are currently working on developing an HTML5/JavaScript application specifically designed for tablet devices. Our main goal is to create different screen layouts for landscape and portrait orientations. Initially, we attempted to detect orientation cha ...

Header formatting issue when attempting to implement tablesorter plugin

I implemented the widget-scroller and widget column Selector in my table using the table sorter plugin in jQuery. Has anyone encountered a problem like the one shown in this picture? It seems that my table headers do not align with the columns properly an ...

Issues with React's useState hook not updating properly

As a React beginner, I am facing an issue with my input field filtering functionality. The problem arises when the results are filtered and rendered, as it seems to be ignoring the last character of the input value. For instance: If I type in "s", nothing ...

Discovering the closest major urban area using geonames

One of my PHP functions retrieves the closest nearby city based on a given latitude and longitude: function findCity($lat, $lng, $username) { $json_url = "http://api.geonames.org/findNearbyPlaceNameJSON?lat=" . $lat . "&lng=" . $lng . "&us ...

SB Admin 2 menu with multiple levels does not collapse as expected

I'm in the process of integrating the menu from the sb admin 2 template into my Ruby on Rails application: As I gradually added components to test functionality, I successfully implemented the top and side nav bars. However, I encountered an issue wi ...

Exploring uncharted territory with the Navigator component in React Native

I am experiencing an issue with undefined navigator when using React Native MessageTabs: _onPressItem = (item) => { const { navigate } = this.props.navigation; //console.log(JSON.stringify(item)); navigate('SingleConversation', {id ...

Troubleshooting: Bootstrap 5 Alert not Displaying on Website

I'm experiencing an issue trying to display a bootstrap alert in my HTML code. Here is the code I'm using: <div class="alert alert-success alert-dismissible fade show" role="alert"> text & ...

Is it possible to utilize Javascript instead of PHP Curl to present JSON API data?

After successfully displaying JSON API data from openweathermap.org on my HTML webpage using PHP Curl, I am now seeking help to achieve the same output using Javascript. My PHP script retrieves JSON data from the source, and here is a snippet of that PHP c ...

What is the process for modifying the popups associated with a polygon object?

As of now, every time I click on the map, a popup shows up with the name of the country based on a geoJSON file containing multi-polygon lnglat coordinates that outline the borders of each country. This method saves me from manually inputting each country& ...

What is the best way to combine sub-values into arrays using jq?

As I am new to jq, I am trying to extract the values from the images keys and store them in a new key. Can anyone help me with this? { "environments": { "staging": { "apps": { "web": { "image": "image1" } } ...

Angular is throwing an error during generation

After manually installing nodejs and npm on my ubuntu 14.04, I checked the versions: root@wemet:~/ang# npm version { http_parser: '1.0', node: '0.10.34', v8: '3.14.5.9', ares: '1.9.0-DEV', uv: '0.10.30', z ...

Finding the smallest value for each day in MongoDB using Mongoose

I have a collection in my MongoDB database called measured_data that includes entries for each day containing the fields measured_at and value. I am looking for a way to use Mongoose to find the lowest value recorded for each day. Any insights or suggest ...

I am looking to eliminate the double quotation marks from a JSON file so that I can properly utilize

How can I successfully save a JSON return into an NSDictionary when there are spaces and double quotes present in the data? Is it possible to parse SBJSON to remove the double quotes before saving to rowsArray? rowsArray: { Rows = ( { ...

Webpack is having trouble resolving the specified file or directory

MyAPP: |--src   |--index.js   |--content.js |--webpack.config.js index.js : const React = require('react'); const ReactDom = require('react-dom'); const View = require('./content'); ReactDom.render(<View/ ...

What is the best way to change a JavaScript variable into a PHP variable?

I am interested in converting my JavaScript variable to a PHP variable... Currently, I have the following scenario - in the code below there is a variable e, but I would like to utilize e in PHP as $e: <script> function test() { var e = documen ...