Tips on passing a JSON object from JavaScript to ASP.NET

I attempted to invoke a method in an asp.net controller using a json string/object from javascript.

The asp.net controller code is as follows:

public class HomeController : Controller
{

     public ActionResult doWork(string data) {
          // dowork..
          return new EmptyResult();
     }
}

Within the javascript, I have the following snippet:

var XHR=new XMLHttpRequest();
XHR.open("GET", 'http://localhost:58476/home/dowork', true);
XHR.setRequestHeader("Accept","application/json");
XHR.onreadystatechange = function () {
    if (XHR.readyState == 4 && XHR.status == 200) {
        alert('ok');
    }else{
        alert('not ok');

    }
};
XHR.send(JSON.stringify(queryResult));

When the javascript runs, it calls the dowork method in asp.net, but the data parameter is null. The onreadystatechange event triggers the 'not ok' alert.

In my console log, I discovered the error message:

XMLHttpRequest cannot load http://localhost:58476/home/dowork. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

Does anyone know how to resolve this issue?

Answer №1

Consider implementing the Access-Control-Allow-Origin header to solve this issue easily.
Simply add the following code snippet to your web.config file:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Additionally, ensure that you are sending data through a POST request instead of a GET request. For more information on the send method, visit w3schools.
To make this change, modify your XHR.Open method to

XHR.open("POST", 'localhost:58476/home/dowork', true);

Answer №2

It's clear that the JavaScript code is making a request to a server different from the one where the page originated.

The first server is operating on port 8081, while the other is running on port 58476.

Because of the same-origin policy, AJAX requests can only be sent to the server hosting the JS script.

Although it is possible to disable this security measure, it is not advisable unless you are aware that someone could insert JavaScript code into your page and use it to send sensitive data, such as authentication cookies, to their own server.

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

Issues with Jquery DataTables Component not functioning as expected

I'm a beginner in jQuery and I downloaded this but there aren't enough tutorials available. If anyone knows how to do this correctly, please help me out. It's been difficult for me to figure it out because when I search online, I can't ...

Redirecting CORS in Cordova: A Comprehensive Guide

My Cordova/Phonegap app is encountering an issue while trying to retrieve certain files using AJAX. The specific error message that I receive states: XMLHttpRequest cannot load https://docs.google.com/uc?export=open&id=.... Redirect from 'https ...

"Incorporating a hyperlink into a newly added table row with the help

When utilizing jQuery, I am able to dynamically add rows to a table with each row containing an anchor tag. However, when attempting to populate the anchor tags with links using jQuery, the links do not appear as expected. Strangely enough, the other data ...

Sorting JSON output with usort function

I have a JSON output below. Can someone please advise on how to sort this based on the "no_count" column? $arr= {"UserHeader":[ {"id":"154", "no_count":15}, {"id":"155", "no_count":11}, {"id":"158", "no_count":13}, {"id":"159", "no_count":31}, {"id":"164 ...

Driver Process terminated - session not initiated: The ChromeDriver version is incompatible with the Chrome version

Encountering a mismatch error when trying to set up the ChromeDriver for running selenium tests in C# results in the chromedriver executable continually running. After adjusting the code to catch the exception and use Driver.Quit(), there is still no impa ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

Is it possible for Cypress to execute test files that are imported from outside of the Cypress folder

Currently, I am developing an E2E test framework using Cypress and encountered an issue while trying to import spec files from locations outside the traditional Cypress directory structure (which includes directories for fixtures, integration, plugins, and ...

How come running `npm install <folder>` results in installing different dependencies compared to `npm install lib`?

My current project, project1, relies on <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5221262b3e37367f313d3f223d3c373c262112667c6">[email protected]</a>. When attempting to integrate project2 into project1 as a ...

"Facing an issue with Google Chrome not refreshing the latest options in an HTML select dropdown list

Having trouble creating an offline HTML file that incorporates jQuery for the script. The page features a state select menu followed by a second menu for counties. When a state is selected, only the corresponding counties should display while others remai ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

Error: The strategy for authentication is not recognized as "login" - Express and Passport

I am currently experimenting with a basic MEAN stack tutorial I found online. The technologies involved are: Node.js Express.js Passport.js Below is the code snippet for the application file: app.js var express = require("express"); var mongoose = req ...

Transferring Data from Google Sheets to Excel 2016

Currently, I am developing a console application within the .NET framework that facilitates the upload of a .XLSX file to Google Drive. This process involves converting the file to Google Sheets format. Additionally, the application allows for the download ...

Optimizing Variable Destructuring Efficiency

Is there a difference in performance when assigning variables like const color = props.color; compared to destructuring like this const { color } = props; Furthermore, does destructuring within the parameters affect performance positively or negatively ...

retrieving information from an array of objects within a nested JSON array

Struggling to extract information from an API set. When viewed in Postman / Insomnia, the body looks like this: { "responses": { "log": [ { "id": 123, "date": "2022-01-01T01:12:12.000Z", ...

The API response indicating success is simply denoted as "Success: True", without any accompanying data

I've set up my application on an express server with a proxy to communicate with the API server. Here's a snippet of my code: HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Steps to finish (refresh) a mongoDB record

Currently, I am dealing with the following scenario: An API request from one service is creating multiple MongoDB documents in a single collection. For example: [ {_id: 1, test1: 2, test: 3}, {_id: 2, test1: 3, test: 4} ] Subsequently, a second service ...

warning: issue detected with the password value in jquery

Why is the following script generating an incorrect JavaScript alert message? <script type="text/javascript> $('#cpassword').change(function() { var pass=$('#password').val(); alert(pass); var cpass=$(& ...

How to retrieve data from an undefined table using Sequelize that is created through association

I've encountered a new challenge while working on my latest project; Imagine the tables User and Project in Sequelize have been defined. There's also a third table in the database called ProjectsUsers, and I need to retrieve data from there. T ...

Setting initial values for an object in JavaScript

I am currently seeking a method to store predefined values in a separate file for populating my function: Here is my function in index.js: const Modes = (array) => { return { name: array.name, funcionarioIncrease: array.funcio ...

Display a modal before leaving the page?

I need to display a modal message when a user navigates away from the page, triggered by a successful AJAX call. The issue is that if the message loads too quickly, the user may not have enough time to read it before being directed to another page. This is ...