Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-19 22:53:01
Original
618 people have browsed it

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>
Copy after login

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);
  }
});
Copy after login

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!"
  });
});
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!