"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: https://i.sstatic.net/OlzTW.png

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

"Troubleshooting when a NodeJS Program Refuses to

Currently facing an issue while attempting to execute a Node program written in JavaScript with no indication of what's causing the problem. The program abruptly ends without providing any error or stack trace. const prompt = require('prompt-sync ...

Steps to gather all the images within a directory

Take a look at this demo When you click on the "next" button, new images are loaded from the internet. In my application, all the images are stored in the img/image folder with names like 1.jpg, hi.png, etc. My question is, how can I display these image ...

Guide on updating individual rows in Google App Script using data from a different sheet

I am trying to create a script that will pull a value from column[3] in the ZONE sheet to the active sheet, specifically in column 56 of the job sheet when the zonelist value matches the zone value in different sheets. The script should check the range fro ...

Problem with transitioning to a different page on Next.js

I am having trouble navigating to a different page in Next.js using the router.push function. The goal is to route to "example.js" by utilizing a variable called ChangePage, which leads to a single div element on that page. However, despite following the ...

The error message "Google Heatmap API - visualization_impl.js:2 Uncaught (in promise) TypeError: Cannot read property 'NaN' of undefined" was encountered while using the

I'm currently working on a project that involves utilizing a JSON data structure like the one shown below: [ { "lat": 53.1522756706757, "lon": -0.487157731632087, "size": 63, "field": "TestField", ...

Solving template strings in a future context

I have a unique use-case scenario where I am filling the innerHTML like this. However, my issue lies in resolving the template literal within the context of a for loop. Any suggestions on how to accomplish this? var blog_entries_dom = 'blog_entries& ...

The debounce function seems to be malfunctioning as I attempt to refine search results by typing in the input field

Currently, I am attempting to implement a filter for my search results using debounce lodash. Although the filtering functionality is working, the debounce feature seems to be malfunctioning. Whenever I input text into the search bar, an API call is trigge ...

Tips for transferring files directly from the front-end to a Google Cloud Storage container

I'm working on setting up a basic Express server and a front-end application. The goal is to send a request from the frontend to the Express server when the user clicks a submit button. The server should then generate a signed URL for a Google Cloud S ...

Are HTML entities ineffective in innerHTML in javascript?

Take this example: <script type="text/javascript> function showText() { var text = document.getElementById("text-input").value; document.getElementById("display").innerHTML = text; } </script> <?php $text = "<html>some ...

Send function arguments to populate dropdown menus with JSON data

Is there a way to pass the parameter into "foodName" from the function that sends the url and id, without explicitly mentioning it in the function? For example, could you create a more generic function like: call('/url/to/foodlist', "foodLis ...

Steer clear of Cross-Site Request Forgery through

As someone who is still learning about web security, I am curious about the best practices for using tokens on JavaScript requests to prevent CSRF attacks. Is it possible for someone to provide a code example? I already know how to implement this properly ...

Node.js memory exhausted following successful file upload

My current setup involves a web-server operating on an embedded Linux platform that runs on an armv7 SBC (Atmel SAMA5D27-SOM with 128MB RAM). To update the firmware, I need to upload a .tar.gz file through this interface, then extract it and perform furth ...

Submitting information to an HTML page for processing with a JavaScript function

I am currently working on an HTML page that includes a method operating at set intervals. window.setInterval(updateMake, 2000); function updateMake() { console.log(a); console.log(b); } The variables a and b are global variables on the HTML page. ...

Sending data from PHP to a text file upon clicking a button

I have been struggling with AJAX and despite my efforts to research on Stack Overflow and other online resources, I still can't get it to work. Any help would be greatly appreciated. My issue involves a formatted JSON file that I am able to parse usi ...

Creating a basic image carousel with JavaScript, CSS, and HTML

After running the code, I encountered an issue where the first image displays but then after one second, only a white blank screen appears with no further action. It seems like there may be an error in the JavaScript code. Below is the code that was attemp ...

Retrieve the value of a variable in a Bootstrap modal using Jade

I am looking to accomplish the following: On my Jade page, I have a for-loop that generates a list of items. Each item has some information displayed through Jade variables and a delete button. When this delete button is clicked, I want a Bootstrap Modal ...

Maximizing efficiency in JavaScript by utilizing jQuery function chaining with deferred, the .done() function

I am working on retrieving data from multiple functions and want to chain them together so that the final function is only executed when all the data has been successfully loaded. My issue arises when trying to use the .done() method, as it calls the func ...

Guide for creating a scroll-triggered rotation animation using only JavaScript

Looking to achieve a cool scroll effect with an image that rotates on the X-axis by a specific degree, such as 70deg. The goal is to have the image's rotateX value change to 0deg when it enters the viewport upon scrolling and revert back to 70deg whe ...

I would appreciate your assistance in comprehending the error that arises when using the DELETE method

Attempting to implement the DELETE route functionality, I am encountering an issue. The goal is to extract the id from req.params and use it to delete the corresponding document associated with that specific id. Below is my code along with the error messag ...

The removal of the Lodash library from node modules is not occurring

In an effort to reduce bundle size, I made the decision to replace all lodash methods with core js methods in my Vuejs project. Despite attempting various npm uninstall commands such as: npm uninstall lodash npm uninstall lodash --save npm uninstall lodas ...