How can CORS be activated? Is it through the server or Javascript, and where does this

Currently, I am testing my ReactJS website on localhost:3333 and my ASP.NET Web API 2 on localhost:54690.

I am utilizing axios for my AJAX requests, but encountering an error when making a request.

XMLHttpRequest cannot load http://localhost:54690/api/Storage/Get. The response to the preflight request does not pass the access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3333' is therefore denied access. The response returned a HTTP status code of 500.

Despite trying to add CORS, it seems like I might be doing it incorrectly. I attempted both server-side and client-side approaches.

   var instance = axios.create({
            baseURL: 'http://localhost:54690/api',
            timeout: 1000,
            headers: { 'Access-Control-Allow-Origin': '*' }
        });

        instance.get('/Storage/Get')
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });

For server-side implementation:

[EnableCors(origins: "http://localhost:3333/", headers: "*", methods: "*")]
public class StorageController : ApiController

WebapiConfig:

  public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Filters.Add(new EnableQueryAttribute());

            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.EnableCors();
        }
    }

Edit:

It appears that by using [EnableCors(origins: "", headers: "", methods: "*")], it works without specifying anything in the header for AJAX. However, this may not be a suitable solution for production, right?

Is there a way to globally configure CORS? It's inconvenient to have to set it up for every controller.

Edit 2:

Further investigation based on the input from @kormali_2 suggests that the issue could be due to having "" instead of "". There might also be a global option available for CORS configuration.

Answer №1

If you want to allow cross-origin resource sharing (CORS) globally, you can do so with the following code:

// Enable CORS globally for any host
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);

To enable CORS only for a specific host, use the following code instead:

// Enable CORS globally for specific host
var corsAttr = new EnableCorsAttribute("http://localhost:3333", "*", "*");
config.EnableCors(corsAttr);

For more information on enabling CORS in ASP.NET Web API, visit this link.

Answer №2

Give this a shot:

    let request = axios.create({
        baseURL: 'http://localhost:54690/api',
        timeout: 1000,
        headers: { 
         'Accept': 'application/json',
         'Content-Type': 'application/json',
         'Access-Control-Allow-Origin': '*'
        }
    });

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

What is the best way to divide my Vue.js project into separate sections for development and testing purposes?

I am looking to split my vuejs frontend project into two sections: development and testing. For the development section, I want to work locally and make requests to the example:8010 url, while for the testing section, I need to send requests to the example ...

Conceal a different div unless it includes

Hi everyone, I need help with a filter code snippet: $(".title").not(":contains('" + $("[name=filter]").val() + "')").hide() The issue I'm facing is that the .title class is nested within the .sortAll class along with many other divs. I w ...

Including JavaScript in HTML Error 404

https://i.stack.imgur.com/aQDPG.png I am struggling to understand why this import is not functioning as expected. I have tried using script/import.js but it still fails to work. The error message I keep receiving is: 127.0.0.1 - - [09/Sep/2020 15:09:35] ...

Unable to get the deletion functionality to work for Dropzone.js and PHP script

I am currently using dropzone to handle file uploads. My goal is to delete the files on the server when the user clicks on the removeLink. I have implemented an Ajax function that calls a .php site for this purpose. However, I am facing an issue where I am ...

What is the best method for choosing the next item with jQuery?

I am facing an issue while trying to apply some design on the next element. The error message that I am encountering is: Error: Syntax error, unrecognized expression: [object Object] > label Below are my selections for browsing by category: BROWSE BY ...

Should one consider using requirejs to enhance individual pages instead of relying solely on vanilla JavaScript applications?

I have a question regarding the practical use of RequireJS. After learning about purely JavaScript-driven web pages, I have been enhancing individually rendered views (often provided by a PHP Framework) with AngularJS to add more functionality. However, m ...

Highlighting table column when input is selected

I am working with a table where each <td> contains an <input>. My goal is to apply the class .highlighted to all the column <td>s when an <input> is being focused on. Additionally, I want to remove this class from all other columns ...

Utilizing Vue to create a button within a popup window

Utilizing the vue2-google-maps package, I have created a custom popup. Within this custom popup, there is a button that is intended to open a new popup in place of the existing one. Here is the HTML code: <gmap-info-window :options="infoOptions" : ...

An internal server error has occurred within the asp.net framework, resulting in

Seeking Solution: Currently, I am in the process of developing an application where I have implemented an HTML select list to choose a category. Using AJAX web method, I am trying to retrieve items and their respective images based on the selected category ...

Show the time in hours and minutes (00:00) while rounding off seconds to the nearest minute

I need the time to always display with leading zeros when less than 10. For example, if a task took 3 hours, 7 minutes, and 33 seconds, it should be shown as 03:08. Currently, I have the buttons disabled after they are clicked to prevent restarting the ti ...

Receive the response text from a PHP script following an AJAX call

I am looking to insert data into my database and receive the response from PHP that interacts with the database. Here is a snippet of JavaScript code: var request = $.ajax({ type: "POST", url: "nieuwDuel.php", data: dataString, success: function(response ...

Alter the hue of a component upon being clicked

Seeking help to modify the color of my menu elements upon clicking on the "center" or "right" containers (reverting back when clicked again). Currently, the three lines in my menu are white, but I desire them to turn red when either of these containers is ...

Response from the controller upon choosing a value from the selection dropdown

Scenario: In this scenario, there are two tables in consideration: Firm table : ID (string), Firm(string) Firms table: FirmID(string FK), Name(string) The goal is to select a value from the Firm table, pass it to the controller as Firm, and then execut ...

Tips for outputting a message to the console from a Ruby controller when a method is triggered by an AJAX call

I am trying to display a message in the console from a Ruby Controller using an AJAX call to invoke a method. I have attempted various methods to achieve this: Rails.logger.debug("debug::" + person.name) puts "test" logger.info("session info" + ...

The Angular UI Datepicker is not reflecting changes in scope variables within the dates-disabled function

I'm currently working with AngularJS and the Angular UI Bootstrap. I've encountered an issue that I initially thought was related to scope, then initialization, but now I'm stuck trying to figure out what's causing the problem. I' ...

What is the process for adding elements to the parent elements that have been selected using getElementsByClassName?

Here is the JSP code snippet I'm working with: <% while(resultSet1.next()){ out.println("<p class='comm'>"); out.println(resultSet1.getString("answer_content")); ...

Automatically change and submit an <input> value using jQuery

I have been working on a prototype to enable users to access all the data associated with a visualization. The idea is that they would click on a specific point, triggering a modal to appear, and within that modal, a table would dynamically filter based on ...

Discover the proper technique to display an error message in cases where no data is detected during the filtering process

I'm currently working on a component that involves search filtering and dropdown filtering. The filtering functionality is working fine, but I'm struggling to determine where to display an error message if no data is found during the filtering pr ...

Simple methods for ensuring a minimum time interval between observable emittance

My RxJS observable is set to emit values at random intervals ranging from 0 to 1000ms. Is there a way to confirm that there is always a minimum gap of 200ms between each emission without skipping or dropping any values, while ensuring they are emitted in ...

Issue regarding the slash format in credit card expiration dates

When entering the credit card expiration date, I am currently facing an issue. Every time I input two numbers, I need to manually add a slash (/) after them. However, if I try to delete the third number, it only removes one character. Is there a way to mak ...