0

My application has 2 parts. React project is for front end and Web API is for services/backend.

I am trying to access GET API endpoint in React using Fetch. My REST API application framework in .net 7.0. I have setup CORS in startup Program.cs and also tried making adjustments in React call. I am sharing my code for both Web API and React.

I make sure my endpoint is returning result, I check that through Swagger.

Now my issue is - when I try to access the API from React component, I get following error.

   **Access to fetch at 'http://localhost:5152/api/product' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.**

I tried various references such as below to rectify this code but nothing helped. If I gain some insight on which code base (API or React) needs to be amended, that is wonderful and appreciated.

My Web API code:

Controller:

    [Route("api/product")]
    [ApiController]
    [EnableCors(origins: "http://localhost:5152", headers: "*", methods: "*")]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            List<Product> products = new List<Product>();
            products = _productService.FetchProducts();
            return new JsonResult(products);
        }
    }

React Component code:

    import React, { useState, useEffect } from 'react';
    import axios from 'axios';

    function ProductDropdown() {
    const [products, setProducts] = useState([]);

    useEffect(() => {
        fetch('http://localhost:5152/api/product', 
            {
                mode: "no-cors",
                headers: {
                    "Access-Control-Allow-Origin": "*"
                    
                }
            }).then(function (response) {
                console.log(response.status);
                //Check if response is 200(OK) 
                if (response.ok) {
                    console.log("welcome ");
                    console.log(response.data);
                    setProducts(response.data);
                    alert("welcome ");
                }
                
                //if not throw an error to be handled in catch block
                //throw new Error(response);
            })
            .catch(function (error) {
                //Handle error
                console.log(error);
            });
    }, []);

    return (
        <select className="prodSelect">
            <option value="0">Select product</option>
            {
                products.map((p) => (
                    <option key={p.productId} value={p.productId}>
                        {p.products}
                    </option>
                ))
            }
        </select>
    );
}

export default ProductDropdown;
Binoy
  • 390
  • 5
  • 19
  • Have you customed the `EnableCors` attribute? The default `EnableCors` only have one parameter for `PolicyName`. You can refer to this [link](https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0#attr) – Xinran Shen Mar 31 '23 at 08:56
  • `no-cors` is almost never what you want. It removes your ability to read the response body and other things. – Evert Mar 31 '23 at 09:38

1 Answers1

0

You have to add this

"Access-Control-Allow-Origin": "*"

in server side, not in React side.

you can look into this How to enable CORS in ASP.NET Core