Django/react Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response

I am building a website using django as purely a server and React. I am getting the error

Access to XMLHttpRequest at 'http://localhost:8000/dividends/current_yield/hd' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

so far i've tried Redirect is not allowed for a preflight request and "No 'Access-Control-Allow-Origin' header is present on the requested resource" in django

I added corsheaders to my installed apps in django, and still no luck

my app.js looks like

import React from 'react';

import SearchBar from './SearchBar';

import axios from 'axios';


class App extends React.Component {

  onSearchSubmit(term) {
    axios.get('http://localhost:8000/dividends/current_yield/hd', {
      // params: {query: term},
      headers: {
        // Authorization: 'Client-ID *YOUR KEY HERE*'
        // "Access-Control-Allow-Origin": "*",
      }
    }).then(response => {
      console.log(response.data.results);
    });
  }

  render() {
    return (
      <div className="ui container" style={{marginTop: '10px'}}>
        <SearchBar onSubmit={this.onSearchSubmit} />
      </div>
    )
  }
}


export default App;

my views looks like

def current_dividend_yield_view(request, ticker):
    yahoo_stock_obj = yfinance.Ticker(ticker.upper())
    price = get_current_price(yahoo_stock_obj)
    dividends = get_all_dividends(yahoo_stock_obj)
    current_yield = get_current_dividend_yield(price, dividends)
    current_yield_object = {'current_yield': current_yield}
    data = json.dumps(current_yield_object)
    return HttpResponse(data, content_type='application/json')

my settings.py

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'dividends_info.apps.DividendsInfoConfig',
    
    'corsheaders',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',

    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',

    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


""" custom settings below here """

CORS_ORIGIN_ALLOW_ALL = True

# https://stackoverflow.com/questions/53215045/redirect-is-not-allowed-for-a-preflight-request
CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

If I can get this working the rest of my workweek will go well, but for some reason the answers regarding Django didn't help me. I now know this is serverside issue only and giving headers from the axios request won't help. Any help appreciated

You need to modify your settings.py to allow your frontend to access the service via CORS, make sure to add your correct frontend port:

# Add here your frontend URL
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
]
Back to Top