0

I am working on a project with Django that serves data through API via Django Rest Framework on a React frontend. The Browsable API works fine, however, the react frontend is giving an error in the console.

I have installed django-cors-headers successfully.

import './App.css';

  class App extends Component {
      state = {
        products: []
      };

      async componentDidMount() {
        try {
          const res = await fetch('http://127.0.0.1:8000/products/');
          const products = await res.json();
          this.setState({
            products
          });
        } catch (e) {
          console.log(e);
        }
      }

      render() {
        return (
          <div>
            {this.state.products.map(products => (
              <div key={products.id}>
                <h1>{products.prodName}</h1>
                <span>{products.description}</span>
              </div>
            ))}
          </div>
        );
      }
    }

    export default App;

Access to fetch at 'http://127.0.0.1:8000/products/' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.

1 Answers1

0

these are parameters to check: 1. Add this line in the MIDDLEWARE in (setting.py)

'corsheaders.middleware.CorsMiddleware',
  1. make sure that you have this:
CORS_ORIGIN_WHITELIST = (
   'localhost:3000/'
)
  1. Also Check This :
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)

all of this prameters in your setting file (setting.py)

  1. You write fetch('http://127.0.0.1:8000/products/') so in your url.py make sure about back slash:
path('products/', views.products,name='products')
OAH
  • 1,160
  • 2
  • 11
  • 24