Home  >  Article  >  Web Front-end  >  How to Resolve the \"Unexpected Token :\" Error When Using jQuery.ajax to Fetch JSON from Node.js?

How to Resolve the \"Unexpected Token :\" Error When Using jQuery.ajax to Fetch JSON from Node.js?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-19 22:53:01619browse

How to Resolve the

Unexpected Token Colon JSON in jQuery.ajax#get

Problem:

When using jQuery.ajax#get to retrieve JSON data from a Node.js API, a "Unexpected token :" error occurs in Chrome.

Context:

  • Server-Side Code: A Node.js Express server returns JSON data in the format: {"Name":"Tom","Description":"Hello it's me!"}.
  • Client-Side Code: An AJAX get request is made in a jQuery script to retrieve the JSON data.

Investigation:

Examining the error in Chrome suggests that the JSON response contains an unexpected colon (:).

Solution:

Enabling JSONP Support:

The issue arises because the client is expecting JSONP response, which is JSON data wrapped in a JavaScript function call. To enable JSONP support, the server must include the "Padding" ("P") in the response.

<code class="text">jQuery111108398571682628244_1403193212453({"Name":"Tom","Description":"Hello it's me!"})</code>

Server-Side Code Modification:

To support JSONP in Node.js Express, modify the server code as follows:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  const callback = req.query.callback;
  const data = {
    Name: "Tom",
    Description: "Hello it's me!"
  };

  if (callback) {
    res.setHeader('Content-Type', 'text/javascript');
    res.end(callback + '(' + JSON.stringify(data) + ')');
  } else {
    res.json(data);
  }
});

Alternatively:

Use ExpressJS's built-in res.jsonp() method:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.jsonp({
    Name: "Tom",
    Description: "Hello it's me!"
  });
});

Client-Side Code Modification:

No modifications are required on the client-side. By default, jQuery will pass the callback query-string parameter with the function name.

The above is the detailed content of How to Resolve the \"Unexpected Token :\" Error When Using jQuery.ajax to Fetch JSON from Node.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn