Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I utilized jsonp. However, upon completion of the request and retrieval of the data within the callback function, an error is displayed:

Uncaught SyntaxError: Unexpected token :
. Here are snippets of the server and client codes:

Server

var express=require('express');
var app = express();
var http = require('http').Server(app);
var port=Number(3000);
var server_ip_address = '127.0.0.1';

http.listen(port,server_ip_address, function(){
   console.log('listening on '+port);
});

app.get('/test', function (req, res) {
   console.log(req.query);
   res.send({message:'hello'});
});

Client

$.ajax({
    url: 'http://localhost:3000/test',
    type: 'GET',
    dataType:'jsonp',
    crossDomain:true,
    data: {
        username: $('#username').val(),
        password: $('#pwd').val()
    },
    success: function(result){
        console.log($.parseJSON(result));
    },
    jsonp:'jsonp'
});

Within the server code, I attempted using

res.setHeader('Content-Type', 'application/javascript');
res.send({message:'recieved'});

as well as

res.setHeader('Content-Type', 'application/json');
res.send({message:'recieved'});

In the client side, I tried logging the result object directly without success. Any assistance would be greatly appreciated. Additionally, suggestions for alternative methods of fetching data are welcomed. Thank you in advance.

Answer №1

If you want to simplify the process, just utilize res.jsonp() instead of manually setting headers:

app.get('/test', function (req, res) {
   console.log(req.query);
   res.jsonp({message: 'hello'});
});

The default callback parameter is typically callback, but it can be changed if necessary, like this:

app.set('jsonp callback name', 'cb');

note: It may be necessary to remove the jsonp:'jsonp' from your client-side code since it specifies the callback name. Additionally, consider switching from a GET to a POST request when submitting data, especially sensitive information.

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

The error message, "Property 'message' is not found on type 'ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>.ts(2339)", indicates that the requested property is not present in the specified type

Hello there! Recently, I implemented a custom error handling middleware in my Node.js TypeScript application. However, I encountered an issue where it is showing an error stating that 'message' does not exist on type 'ErrorRequestHandler&apo ...

Ways to verify the nodemon version that is currently installed on your local machine

On my Windows 10 machine, I recently installed nodemon locally in a project and now I'm curious to know which version is installed. Can someone please share the command to check the version of nodemon without needing to install it globally? My aim is ...

In Swift, quotation marks are dropped from dictionary keys and values when a variable is passed in as AnyObject

When working with a dictionary in Swift of type [String: AnyObject], I encountered an issue where the key:value pairs of nested dictionaries were losing their quotation marks. The outer dictionary had strings enclosed in quotation marks, but they were miss ...

Adjusting the content within a text area using an AngularJS service

I am currently editing text in a textarea within the admin view and I would like to display it through an angular service on the user view. However, I want the text to be displayed in multiple rows, maintaining the same format that I entered in the textare ...

What is the best way to apply index-based filtering in Angular JS?

I am working on a tab system using ng-repeat to display tabs and content, but I'm facing some challenges in making it work seamlessly. Below are the tabs being generated: <ul class="job-title-list"> <li ng-repeat="tab in tabBlocks"> ...

Tips for transferring a variable from a hyperlink to a Flask application

Here is a snippet of my Python Flask code: @app.route('/ques/<string:idd>',methods=['GET', 'POST']) def ques(idd): print(id) And here is the accompanying Javascript code: var counts = {{ test|tojson }}; var text = ...

Having trouble with json_decode in PHP? Learn how to effectively retrieve JSON data in PHP

My attempt to update content using Angular on the front-end and PHP on the server side is encountering some issues. Below is the code snippet being used: In the main js file, a call for update: updateinscription: function($params) { var urlphp = "ht ...

What are the steps to interpret this JSON information?

Looking for guidance on how to interpret JSON data fetched from the server? { "DS": { "LST": [ { "OID": 1, "OCD": "1", "OPE": "AIRCEL", "IPH": "Images/provider/aircelsm.jpg", ...

Enhancing the templateUrl with additional value in AngularJS and PHP

I am having trouble capturing the value of the {fold} and adding it to the templateUrl. The php file show.person.php is returning an error because it is only recognizing 'id' as '{fold}' and not as a number like '54' In my co ...

"Utilizing jQuery to access nested JSON structures. I am looking to access nested arrays within a JSON

{ "data": [ [ { "Id": 2, "Name": "John Doe", "city": "New York", "location": "Times Square", "landmark": null, "pincode": 12345, ...

The jQuery function is returning an inaccurate value for the height of

In my Cocoa (Mac) application, I am utilizing a Webview and trying to determine the accurate height of a document. While the typical method webview.mainFrame.frameView.documentView.bounds.size.height works well in most cases, I encountered an issue with on ...

Having trouble getting CSS Animation to work in a React project?

I am currently developing a Next.js application using React. const partyButton = useRef(null) const handleParty = () => { setTimeout(() => { partyButton.current.classList.add('party-time'); console.log(party ...

Determining the Existence of Duplicates in an HTML Table with Multiple Inputs Using JavaScript

After spending countless hours on research with no luck, I've finally come to seek assistance from you. In my form, I have an input field and a select field, along with a table generated using PHP from my database that displays team names and their r ...

Tips for maintaining a stationary element with fluctuating height positioned at the bottom in React

I am trying to create a fixed element with dynamic height, meaning its size changes when the browser window is resized. You can see an example of what I'm talking about here: https://stackblitz.com/edit/react-yuqarh?file=demo.tsx This element acts li ...

"Encountering issues with running Mongoimport on Mac due to a variable within the

I am encountering an issue while attempting to import a JSON file into MongoDB. Interestingly, when I use this specific command, the file imports successfully: mongoimport -d reps_development -c users --jsonArray --file ~/reps/scripts/mockUserData.json H ...

Unable to Show the Contents of the Item - AngularJS

I'm in the process of developing an application that will showcase job details within a modal window based on the selected template. To achieve this, I've integrated ui.bootstrap and ui.router. However, I'm encountering difficulties in displ ...

"What could be the reason for the malfunctioning of this php/ajax code

I am currently facing an issue with a live search functionality on my website. The search is working fine for two out of the three radio buttons - "Professor" and "Department". However, the code related to the "Course" radio button doesn't seem to be ...

Running Jasmine asynchronously in a SystemJS and TypeScript setup

I am currently executing Jasmine tests within a SystemJS and Typescript environment (essentially a plunk setup that is designed to be an Angular 2 testing platform). Jasmine is being deliberately utilized as a global library, rather than being imported vi ...

The installation of Mutler module in Node.js is encountering errors

Recently, I've been attempting to set up the mutler module in order to upload files with node.js. Unfortunately, I continue to encounter this error message during the installation process for mutler: karans-MBP:artink Karan$ sudo npm install mutler - ...

Fix the JQuery error: JSON string is invalid

Encountering a json error when attempting to create a pie chart using a dropdown menu and api, specifically for the table displaying an invalid string. Pie file <?php $dbHost = 'localhost'; $dbUsername = 'root'; $dbPassword = &apo ...