Model-View-Controller CORS Policy

I have been facing a similar issue as described in , but unfortunately, the accepted solution did not work for me.

The problem I am encountering is with making an ajax request from a client script. The request works perfectly fine locally, but when running it on a test server, it fails.

Here is a snippet of my ClientScript.js:

var AppViewModel = function () {
var self = this;

self.Refresh = function () {
    $.ajax({
        url: "http://localhost/AppName/ControllerName/GetData",
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, jqXHR) {
            //perform actions here
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //handle errors
        },
        complete: function (jqXHR, textStatus) {
            //additional tasks
        }
    });
}

To address the CORS issue in my MVC web service, I have added the following function to global.asax.cs:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://testdev");
    }

Despite implementing the above changes, the error persists while deploying to the "testdev" server:

XMLHttpRequest cannot load http://localhost/AppName/ControllerName/GetData.
Origin http://testdev is not allowed by Access-Control-Allow-Origin.

What could be missing or causing this issue?

Answer №1

It appears that you are currently utilizing an absolute URL (

http://localhost/AppName/ControllerName/GetData
), which is only functional on your local environment. Consider altering it to a relative path like the following:

url: "/AppName/ControllerName/GetData",

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

Error: Value of incoming scope in Angular Directive is not defined

When working in html, I passed an object into a directive like this: <lcd-code ldcCode="{{ detail.program.ldcCode }}"></lcd-code> The value of detail.program.ldcCode is "PSIH"... However, in the Directive, it is showing up as undefined: var ...

Issue: AjaxLazyLoadPanel freezes after loading initial panel

Utilizing a Wicket AjaxLazyLoadPanel to display a list of items, with each item having its own panel. The functionality works as expected except for situations where the user navigates directly to the page in a fresh browser session without visiting any ot ...

Background Patterns on Webpages

My website has a lovely gradient background on the html tag in css, while the body tag showcases a seamless pattern repeating on both the x and y axes. Everything was looking great until I checked the website on an iPad/iPhone in portrait mode, where the ...

Transforming the JSON data into a text format

I have a JSON object structured like this: { "name": "ok", "country": "US", "phone": "900", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f70745f727e767331707c">[email protected]</a>", ...

send a request to ajax asp net for a post

How can I access the post parameter sent to the controller? Ajax script: function sendAjaxRequest(url, method, param) { var AjaxUrl = url; var type = method; if (param == null) var param = ''; $.ajax({ url: AjaxUrl, type: type, ...

The controller method fails to pass a value to the extended controller

There is a scenario where one controller extends another: I am looking to store the result of the second controller's method into a variable in the first controller First Controller: angular.module('Gestios').controller('EmpresasCont ...

Is it possible to customize the pagination-control labels from numbers (1 2 3) to different values, such as 'Anything1 Anything2 ...', by utilizing ngFor* with an array in ngx-pagination?

Is there a way to customize ngx-pagination's pagination control? Currently, the page numbers are displayed as '1 2 3' but I would like to replace them with specific string values from an array. <pagination-controls (pageChange)=& ...

Rendering a child component beyond the confines of its parent component in React.js: A Step-by-Step Guide

I am working with a table component that has sticky headers and dropdowns, ellipsis menus, and other complex components within the table body rows. Each row of the table contains nested table body rows, and the parent rows stick to their child rows. Howeve ...

Adjusting the background element of a fullpage.js layout during resizing and customization

Is there a way to make the background image responsive on a fullpage.js page, specifically for mobile and tablet devices? How can I ensure that a specific part of the image stays at the center of the page when resizing? For instance, in the provided imag ...

Select the initial item in a listbox by default using JQuery

I am receiving JSON response from the controller and using jQuery to populate a listbox. How can I set a default item to be selected in the listbox? Below is my code snippet: if (response.Assets.length > 0) { var list = []; for (var key ...

Looping through ajax calls depending on the status of a particular key

Utilizing a combination of jQuery, Ajax, and PHP, I have successfully implemented a system to query and display data from a database. The process involves submitting data to an Ajax page, as demonstrated below. Submitting an Ajax Request $('#mainInp ...

Looping in REACT with state updates can cause the values to be overwritten

I'm encountering a problem with my function in React that updates the state. It fetches data from a URL in an array and creates a new item, but when trying to update another state array with this new object, it keeps overriding the first item each tim ...

Design an interactive table featuring rowspan functionality

Working on a project with React and attempting to build a dynamic table. Here is an example of how the table should look: https://i.sstatic.net/oEd7q.png The object being used: [ {category: "Type One", subCategory: "One", val: 1, rowSpan: 4}, {category: ...

Sending additional information to my subsequent callback function

Can anyone help me figure out how to pass the variable intermediateData to my second callback in the current scenario? I am struggling with this and would appreciate any guidance. const unsubscribe = firebase .locations() .once('value& ...

Identifying Elements Generated on-the-fly in JavaScript

Currently, I am tackling the challenge of creating a box that can expand and collapse using regular JavaScript (without relying on jQuery). My main roadblock lies in figuring out how to effectively detect dynamically added elements or classes to elements a ...

Optimal approach for integrating an ionic mobile app with Django to streamline form processing

Currently in the process of developing a mobile application with ionic technology. In the case of a traditional django website, we typically create context within the view and pass it to the template, where the HTML is displayed using various methods such ...

Updating a field in React based on the value of another: A step-by-step guide

When designing an exchange interface, I included two input fields that update based on the exchange rate provided. Users are able to input values into either field. An issue arises when a user inputs 5 and receives 500 in the other field. If they then rem ...

What could be the reason why my focus and blur event listener is not being activated?

It seems like everything is in order here, but for some reason, the event just won't fire... const element = (this.agGridElm.nativeElement as HTMLElement); element.addEventListener('focus', (focusEvent: FocusEvent) => { element.classLi ...

Align Bootstrap navigation bar items at the center horizontally

I am currently working on a navigation bar that features two icons, evenly distributed. To achieve this look, I have been experimenting with scaling the icons horizontally in order to make them center-aligned within the navigation bar. However, I have not ...

Sending a value to a specialized component

Presently, I am using a custom component called Search. This component is responsible for rendering a dropdown menu with different options based on the data provided. It also includes a None option by default. const Search = (props) => { const { type: ...