"Encountering a net::ERR_UNKNOWN_URL_SCHEME error message when making an Ajax post request

I'm encountering an issue while attempting to make a post call using Ajax from my frontend to my Express server. The error message I'm getting is net::ERR_UNKNOWN_URL_SCHEME. Here's the code snippet for the Ajax request:

function sendSteps(encodedLatLangs) {
    $.ajax({
        url: 'localhost:3000/route',
        type: "POST",
        dataType: "jsonp",
        contentType: "jsonp; charset=utf-8",
        crossDomain:true,
        data: JSON.stringify({
            steps: encodedLatLangs
        }),
        success: function (response) {
            console.log(done);
        },
        error: function (request,error) {
            console.log('Ajax call gave an error');
        }
    })};

The console output is as follows:

This is how I'm handling the post request on the backend endpoint:

router.post('/route',function (req, res) {
    
    console.log("Hello Received the Data");
    res.send("Hello Received the Data");
    //Perform operations with the received data
});

If anyone can shed some light on this issue, it would be greatly appreciated. Thank you.

Answer №1

When utilizing JSONP, you are restricted to sending solely GET requests (JSONP injects script tags into the DOM).

Your data must consist of a &key=value string and your contentType should be set to application/javascript.

Give it a try:

function transmitSteps(encodedCoordinates) {
    $.ajax({
        url: 'localhost:3000/route',
        dataType: "jsonp",
        contentType: "application/javascript; charset=utf-8",
        crossDomain: true,
        data: 'steps=' + encodeURIComponent(JSON.stringify(encodedCoordinates)),
        success: function (response) {
            console.log('Success');
        },
        error: function (request, error) {
            console.log('There was an error with the Ajax call');
        }
    });
};

Alternatively, utilize JSON (assuming you have control over server settings and can establish CORS).

Answer №2

To allow cross-origin requests, you can set the "Access-Control-Allow-Origin" in the response header. Here is an example of how it can be done. For more detailed information, you can visit https://enable-cors.org/server_expressjs.html. Additionally, it is necessary to remove the "data type" and "content type" from the ajax request.

router.route('/route')
    .post((req, res, next) => {
        controllers
            .post(req.body)
            .then(data => {
                res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
                res.send(message.generateMessage(200, '', data))
            })
            .catch(err => next(err))
    })

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

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

AngularJS: Customize form elements based on model type

I need to work with an Angular model that contains ConfigValues. This is essentially a Dictionary object passed from C# which looks something like this: { Name: "Config Name", Value "True", Type: 0 // boolean } Some of these values are boolean, ...

Tips for creating an effective unit test using Jest for this specific controller

I'm currently grappling with the task of unit testing my Controller in an express app, but I seem to be stuck. Here are the code files I've been working with: // CreateUserController.ts import { Request, Response } from "express"; impor ...

Is there a way to manipulate text in JQuery without altering the inner element?

I am struggling with an issue in my HTML code. Currently, I have the following structure: <h3 id="price">0.00<sup id="category">N/A</sup></h3> My intention is to use AJAX to replace the content within the <h3 ...

What is the best approach for retrieving client-side data when the server has two possible paths?

I am struggling with a situation where my post request on the server side needs to redirect to different routes based on the query result. The code snippet below covers the functionality but fails to change the webpage as intended. app.post('/check&a ...

Fetching the "User ID" variable from localStorage to PHP with angularjs - a quick guide

My goal is to retrieve "Notes" based on the "userID" value. Here is my approach: I used angular.js to trigger the PHP function $scope.getData = function(){ $http.get( '../php/displayNotes.php' ).success(function(data){ $ ...

What are the advantages of using Express.js Router compared to App.use routing?

The Express documentation states that both app.use and Router can serve as middleware by implementing the router interface. This means you have the option to define routes using either of the two methods. For example: app.use(function (req, res, next) { ...

What could be causing the error message "CSRF token missing or incorrect" to appear?

I am facing an issue with returning a value from a View function in Django. This particular function is called from a JavaScript code using Ajax, but I'm encountering an error that says 'Forbidden (CSRF token missing or incorrect)'. JavaScr ...

Should we integrate a MongoDB database calculation app with a POST Controller in sails.js?

The primary function of the application interface is to provide variables that have been initially posted by the client, as well as any subsequent database calculations carried out in real time by a specialized engine. Is it possible to integrate this eng ...

What is the process for uploading an image file to a different server using Express JS?

I attempted to upload an image to another server (13003) using the file/toOther API, but the console output only displayed the following: ------file upload ------- undefined Upon further investigation by checking the console.log(req), I noticed the follow ...

The Jquery flot plugin is failing to plot the graph accurately based on the specified date

I am currently working on plotting a graph using the jquery flot plugin with JSON data. Here is what I need to do: Upon page load, make an AJAX call to receive JSON data from the server. From the received JSON, add 'x' and & ...

What is the method for linking events across multiple objects?

When a user clicks on the confirmation button in a Twitter Bootstrap modal window, I trigger a deletion action on the page. The modal contains two buttons - one for canceling the action and another for confirming it. Once the user confirms the delete act ...

Troubleshooting: React Native and OneSignal notifications not showing up

Currently, I am developing an app in React Native and working on integrating notifications with OneSignal. Although I am able to efficiently receive notifications, I do not want them to be displayed on the screen when they are received. I came across a ` ...

Displaying the number of tasks completed compared to the total number of tasks within a JavaScript ToDo list

Currently, I'm in the process of creating a basic ToDo list using HTML, JS, and CSS. The last task on my list is to display to the user the total number of tasks and how many have been completed. For instance, if there are 3 completed tasks out of 7 i ...

Changing the image source using Javascript and extracting part of the URL

i'm attempting to extract the image url from a series of urls in a loop, removing the hash portion () without the hash (?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDi79vN15idfFETvntyC9yat7FvZQ). I've managed to mak ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Receive a notification for failed login attempts using Spring Boot and JavaScript

Seeking assistance with determining the success of a login using a SpringBoot Controller. Encountering an issue where unsuccessful logins result in a page displaying HTML -> false, indicating that JavaScript may not be running properly (e.g., failure: f ...

Embed a javascript tag to print a PDF document

I have been struggling with printing a PDF file using JavaScript. I attempted to use the embed trick suggested in this Silent print a embedded PDF but unfortunately, the print function remained undefined. Then, I tried another approach using an Iframe and ...

Guide on extracting unique key values from an array by utilizing a different key

I have an array containing the names of products along with their storage capacities. let products = [{name: "samsung A", storage: "128GB"}, {name: "samsung B", storage: "128GB"}, {name: "samsung C", storag ...

Utilizing a JavaScript class method through the onchange attribute triggering

I am facing an issue with a simple class that I have created. I can instantiate it and call the init function without any problems, but I am unable to call another method from the onchange attribute. Below is the code for the class: var ScheduleViewer = ...