飞行前响应中的访问控制允许标头不允许Django/Rect请求标头字段访问控制允许来源



我正在使用Django作为纯粹的服务器和React来构建一个网站。我得到错误

访问'XMLHttpRequesthttp://localhost:8000/dividends/current_yield/hd'来自原点'http://localhost:3000'已被CORS策略阻止:飞行前响应中的访问控制允许标头不允许请求标头字段访问控制允许来源。

到目前为止,我已经尝试过重定向。飞行前请求不允许重定向,并且";否';访问控制允许来源';报头存在于所请求的资源上";在django

我在Django安装的应用程序中添加了corsheaders,但仍然没有成功

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;

我的观点看起来像:

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')

我的设置.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',
)

出于某种原因,关于Django的答案对我没有帮助。我现在知道这只是服务器端的问题,从Axios请求中提供标题不会有帮助。

您需要修改您的设置。要允许您的前端通过CORS访问服务,请确保添加正确的前端端口:

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

相关内容

  • 没有找到相关文章

最新更新