Having difficulty retrieving JSON data from a different domain with Ajax calls

Trying to use JSONP to retrieve JSON from a different domain that utilizes Spring. I have implemented JsonpControllerAdvice:

@ControllerAdvice
public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice {

    public JsonpControllerAdvice() {
        super("callback");
    }
}

The controller looks like this:

@RequestMapping("games")
@RestController
public class GameController extends BaseGameController {

    private static final Logger LOGGER = Logger.getLogger(GameController.class);

    private static final String KAFKA_TOPIC = "virto_games";

    private static final String ROOT_URL = ServerConfig.GAMES_HOST + "/games";

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> games(
            @RequestParam(defaultValue = "0") int page
    ) {
        String url = ROOT_URL + "?page=" + page;
        return request.get(url);
    }
}

The browser returns the following JSON:

{
    "items":[{
        "id":"1b4a3104-925b-46ac-a2da-2187bbf46e0a",
        "name":"Minecraft",
        "description":"Game",
        "user_id":"ee430ea5-0977-4fc2-b1c4-cc33ddd9db56"
    }],
    "number":0,
    "count":1
}

Below is my JavaScript code attempting to retrieve the JSON:

var virtoHost = "http://localhost:8080/";

function getGames() {
    $.ajax({
        url: virtoHost + 'games',
        dataType: 'JSONP',
        jsonpCallback: 'callback',
        type: 'GET',
        success: function (data) {
            alert(JSON.stringify(data));
        }
    });
}

However, it crashes with an exception:

SyntaxError: unexpected token: ':'
[Learn More]
games:1:8

What could be causing this issue? The JSON format appears correct and ':' is a standard delimiter.

Answer №1

After some investigation, I finally figured out the reason for my error. It turns out that AbstractJsonpControllerAdvice is responsible for setting up Jackson to support JSON-P. This explains why Jackson wasn't processing the JSON object sent from the game server in my case.
To fix this issue, I will need to activate JSON-P support on the game server and resend the callback from my aggregation server to the game server.

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

execute various scripts in content_scripts depending on the "matches" provided

I am new to JavaScript and currently working on customizing the script from the MDN tutorial, Your First WebExtension My goal is to draw either a red or blue box around a webpage based on whether it is http:// or https://. But I have encountered a proble ...

Conditional compilation in Laravel Mix allows for specific code blocks to be

I'm currently working on a Laravel project and I need to introduce some conditional statements. Within the root folder of the project, there's a file called module_statuses.json which contains JSON variables like this: { "Module1": true, ...

NodeJS buffer is not capable of handling incomplete TCP stream data

While troubleshooting my TCP JSON stream on the live server, I discovered that if the data streamed to me in JSON format is excessive, it doesn't consistently parse correctly. It requires multiple streams for successful parsing. Here is the code I am ...

nsIProcess - Launch with Background Execution and Deferred Activation

Currently, my method of launching Firefox is as follows: var exe = FileUtils.getFile('XREExeF', []); //this provides the path to the executable var process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess); process.init ...

Can PHP send back data to AJAX using variables, possibly in an array format?

My goal is to transmit a datastring via AJAX to a PHP page, receive variables back, and have jQuery populate different elements with those variables. I envision being able to achieve this by simply writing: $('.elemA').html($variableA); $('. ...

Fetching URL from Right Before Logging Out in Angular 2 Application

I am struggling to capture the last active URL before logging a user out of my Angular 2 app. My goal is to redirect them back to the same component or page once they log back in. Currently, I am using this.router.routerState.snapshot['url'] to r ...

Is it possible to create personalized BBCode?

I currently manage my own forum where users can edit, delete, and report posts and replies. However, I am now looking to add new features such as BBCode. Specifically, I want to implement a [QUOTE][/QUOTE] feature that allows users to easily quote other po ...

What is the most efficient way to check for the presence and truthiness of a nested boolean in Node.js?

There are instances where I must verify the deeply nested boolean value of an object to determine its existence and whether it is set to true or false. For instance, I need to ascertain if payload.options.save is assigned a value of false, yet I am uncert ...

How can VueJS cycle through the arrays within an object?

Is there a way to efficiently iterate through arrays within an object like in this example? I have a simple code snippet that currently outputs indexes in order, but I'm looking to access the values of the array instead. <template> <div&g ...

Issue: Module 'connect' is not found?

Hey there! I'm fairly new to the world of servers, and I've been learning by watching YouTube tutorials. Following one such tutorial, I installed 'connect' using npm in my project folder. Here's the structure of my project: serv ...

When gathering all links in Selenium Java, make sure to exclude the logout link from the loop and proceed with navigation

When I fetch all the links on a page and navigate to each one, there is a Logout link that I want to skip. How can I ignore the Logout link in the loop? I need to exclude the Logout link before proceeding List of links = driver.findElements(By.tagName("a ...

Tips for updating a field using Jquery

For my PHP + MYSQL + JQuery editing form, I am wondering how to display the updated data in the fields without refreshing the entire page after saving it to the database. Currently, I have this code snippet: $(document).ready(function (e) { $('f ...

Collaborative Artistry: Using HTML5, JavaScript, and Node.js for Multiplayer

Creating a multiplayer drawing application for touch-enabled devices has been a challenge. I have utilized Node.js with Socket.io to draw points on a canvas, but there's an issue with the touchend event not resetting properly. To illustrate, take a l ...

In order to successfully utilize Node.js, Async.js, and Listeners, one must ensure

Here is the log output from the code below, I am unsure why it is throwing an error. It seems that the numbers at the end of each line represent line number:char number. I will highlight some important line numbers within the code. Having trouble with t ...

Passing control values as parameters in html.Pagedlist for successful execution

Utilizing a paged list to showcase values has been successful for me. Employing Unobtrusive AJAX, I am able to retrieve data for additional pages. Below is the structure of my paged control: @Html.PagedListPager(Model.CountryList, page => Url.Action(" ...

In order to locate where an object intersects with an array

I am new to the world of javascript. Can someone help me understand how to determine the intersection between an array and object in javascript? Consider the following: var users = [{name:'jony'}, {name: 'raja'}, {name: 'papy ...

Why is the body the last element in Angular modules arrays?

I have a question regarding architectural practices. When defining an Angular module, one common approach is to do it like this: angular.module('app', []) .controller('Ctrl', ['$scope', function Ctrl($scope) { //body.. ...

The component's state consistently reverts to its initial state

I am working with a component called DataGrid that has the following state: const [rows, setRows] = useState([ { id: 1, lastName: 'Snow', firstName: 'Jon', status: 'Sold'}, { id: 2, lastName: 'Lanniste ...

Implement a unique custom mobile menu in place of the traditional WordPress default menu

Greetings! I've embarked on the journey of crafting a personalized WordPress theme using Understrap. My current mission is to replace the existing code for the mobile menu with my own creation. The problem lies in locating the file where the original ...

What's the best way to ensure that the iframe resolution adjusts dynamically to perfectly fit within its container?

iframe-screenshot Displayed in the image are two iframes, but at times I may need to display three. The aim is to ensure that all iframes are responsive within their containers. Below is my existing CSS styling: iframe { width: 100%; height: 1 ...