Home >Web Front-end >JS Tutorial >How to Resolve the \'Unexpected Token :\' Error When Using jQuery.ajax to Fetch JSON from Node.js?
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:
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!