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

Issue with Javascript Date and Time Validation

My application includes code that is supposed to display HTML pages based on today's date and the time of day (morning, afternoon, or evening). However, it seems like there is an issue with how the time is being checked. Currently, at 2:53pm, only the ...

Utilize jQuery to extract all values from the second cell of a table and store them in an array

I have a task that involves pushing numbers from text boxes into an array. These text boxes are located in the second cell of each table row, while the third cell contains a date picker. Currently, the code snippet provided retrieves all values from both ...

Displaying the saved MTRC (markdown-to-react-components) content from the database

I currently have data stored in a database that has been produced using the markdown-to-react-components package as MTRC(content).tree What is the best way to render this content? I've experimented with various approaches, such as dangerouslyInsertHT ...

Disabling a Field in Angular While Preserving its Value

Hey there, late night folks! I have a quick question about Angular. I'm working with a form that includes a specific field where I set the value using patchValue, but I also need to disable this field. The issue is that after disabling it, the value i ...

Bar graph constructed using a pair of div elements

I extracted two values from an array: $target = $data->data[2][32][3]; For this particular example, $target = 9.83%. $clicks = $data->data[1][32][3]; And in this case, $clicks = 7.15%. I have created a bar-like chart using three main div elements ...

Determine whether the browser tab is currently active or if the user has switched to a different

Is there a way to detect when a user switches to another browser tab? This is what I currently have implemented: $(window).on("blur focus", function (e) { var prevType = $(this).data("prevType"); if (prevType != e.type) { // handle double fir ...

Is there a way to launch Visual Studio Code using a web browser?

Is there a way to launch "Visual Studio Code" automatically upon clicking a button on my website? ...

React web app experiencing an issue with MUI Drawer opening flawlessly but failing to close

Recently, I encountered an issue with my React app. I have a Navbar component that displays a Sidebar component when the screen is small, using Material UI for the Drawer functionality. The problem arises when clicking the hamburger icon to open the drawe ...

Efficiently convert a JSON array into an HTML table using the Jquery

Currently, I'm facing a challenge in my project. The issue arises when a query is sent to the server using jQuery, and an array is returned as a response. My struggle lies in transferring this data to a dynamic table since the column count varies with ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

Is there a problem with the way divs are being displayed when using jQuery to show the first 12 elements with the class "hide-show"?

I am encountering a problem with displaying data using the jQuery slice() and show() methods to reveal dynamically generated divs from a PHP function. The code is as follows: <style> .hide-show { display :none; } </style> <div class="c ...

Verifying the visibility status of a div and toggling a class based on it

I'm facing a challenge with multiple checkboxes in a row. When a button is clicked, it displays a div (#locale_container), and flips a small arrow by adding a rotated class. However, I only want the arrow to flip when the div is being shown or hidden ...

Create a new button dynamically within an HTML table row using pure JavaScript programming techniques

Currently, I am retrieving JSON data from an API and then displaying this data in an HTML table using plain JavaScript. My goal is to dynamically add a button at the end of each row for additional functionality, but so far, I have been unable to figure out ...

Proper method for incorporating a single database pool across an Express application

Disclaimer: This issue pertains to singleton objects in Node.js and not DB pools. While developing an Express.js application with the mysqljs node module for DB connections, I am interested in creating a single pool object that can be reused across differ ...

Meteor chat platform now offers the option to create multiple chat rooms

I've been working on an application that features multiple chat rooms. Currently, one of the rooms is functional in terms of sending and receiving messages. However, when I navigate to a different room and try to send a message, the message doesn&apos ...

Send information as FormData object

I'm getting the data in this format: pert_submit: {systemId: "53183", pert-id: "176061", score: 0, q2c: "3\0", q2t: "", …} Now I need to send it as FormData in my post request. Since I can't use an ...

The art of replacing material-ui styles with styled components

As a newcomer to UI material design, I am eager to create my own customized Button Component using styled-components. I am facing a challenge in overriding the CSS based on different button variations such as "primary" or "secondary". You can find my cod ...

Is your window.location.hash malfunctioning?

I am facing an issue with changing the background color of a <div id="services> when a specific link (index.html#services) is clicked. I have attempted to use the latest jQuery along with the jQuery Color plugin from jQuery Color. The code snippet I ...

Looking to Identify a Click Within a Complicated Component and Retrieve the Component's ID

Currently, I am working with React for development and have a need to capture clicks at the topmost parent level for performance reasons. const clickHandler = (e) => { console.log("clickHandler", e.target) --> I want to identify the child ...

Arrange four Divs next to each other with flexbox styling

I've been struggling with aligning my cards side by side. They are a series of divs nested in lists under a <ul> Changing the positioning is not resolving the issue, and I'm hesitant to alter the display as it's crucial for responsive ...