我收到以下错误:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'http://localhost:62570' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
我尝试添加django-cors-headers中间件,并且CORS_ALLOW_ALL_ORIGINS = True我也做了ALLOWED_HOSTS = ['*']但仍然遇到相同的 CORS 错误。我在 NestJS 中遇到了同样的错误,但添加后app.enableCors();它得到了解决。
这是我的settings.py文件:
from pathlib import Path
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
DEBUG = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', …Run Code Online (Sandbox Code Playgroud) python django cors django-rest-framework django-cors-headers
错误详情
单击按钮时生成了两个请求。
到目前为止我搜索了什么?
Axios 通过 Django REST Framework 被 CORS 策略阻止
React 和 django-rest-framework 的 CORS 问题
但无济于事
我在做什么?
从 React 向 DJango API 提交 POST 请求
Django 端设置文件
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = [
"http://127.0.0.1:3000",
"http://127.0.0.1",
"http://localhost:3000",
"http://localhost"
]
CORS_ORIGIN_WHITELIST = [
"http://127.0.0.1:3000",
"http://127.0.0.1",
"http://localhost:3000",
"http://localhost"
]
INSTALLED_APPS = [
......,
"corsheaders"
]
MIDDLEWARE = [
.........,
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
Run Code Online (Sandbox Code Playgroud)
响应 axios 请求
function authenticate() {
let body = {
"email": "ac",
"password": "def"
};
const headers = { …Run Code Online (Sandbox Code Playgroud) 我正在尝试在Django上运行的项目中使用带有JavaScript XMLHttpRequest 的立交桥API http://wiki.openstreetmap.org/wiki/Overpass_API,但我一直在使用
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/accounts/ClientLogin. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Run Code Online (Sandbox Code Playgroud)
错误.无论我是使用GET还是POST,还是来自任何其他主机,我都会收到此错误,而不仅仅是overpass API.
我已经安装了django-cors-headers https://github.com/ottoyiu/django-cors-headers并遵循那里的说明,将'corsheaders'放入INSTALLED_APPS,'corsheaders.middleware.CorsMiddleware','django.middleware .common.CommonMiddleware',进入MIDDLEWARE_APPS,我已经设置好了
CORS_ORIGIN_ALLOW_ALL = true
Run Code Online (Sandbox Code Playgroud)
在settings.py但似乎没有任何工作.我在本地运行它
python manage.py runserver
Run Code Online (Sandbox Code Playgroud)
但我也是在openshift上主持它.在这些工作中,他们都没有给出上述错误.
如果我在这里遗漏任何东西,请告诉我.
我创建了一个非常简单的 Django API。它返回一个固定的数值(仅用于测试目的):
视图.py
from django.http import HttpResponse
def index(request):
return HttpResponse(0)
Run Code Online (Sandbox Code Playgroud)
我还有一个使用 React JS 开发的简单前端。为了开发后端和前端,我使用了这两个教程:
ReactJS:https ://mherman.org/blog/dockerizing-a-react-app/
Django Python API:https : //semaphoreci.com/community/tutorials/dockerizing-a-python-django-web-application
现在我想从 ReactJS 向 Django API 发送 POST 请求并传递name和email参数。我该怎么做?
这是我的 App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
fullname: "",
emailaddress: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const target = …Run Code Online (Sandbox Code Playgroud) 我尝试完全按照本教程所示实现自动完成:https://www.youtube.com/watch ?v=-oLVZp1NQVE
这是教程代码,与我这里的代码非常相似: https: //github.com/akjasim/cb_dj_autocomplete
但是,它对我不起作用。API url 有效,但字段中没有填充任何内容,即没有显示自动完成功能。我可能做错了什么?我正在使用纱线和纱线构建并收集了静态数据,但仍然不起作用。
这是jquery:
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#product").autocomplete({
source: '{% url 'autocomplete' %}',
minLength: 2
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
这是 HTML:
<title>Autocomplete</title>
</head>
<body>
<form>
<label for="product">Product</label>
<input type="text" name="product" id="product">
</form>
Run Code Online (Sandbox Code Playgroud)
以下是观点:
def autocomplete(request):
if 'term' in request.GET:
qs = Model.objects.filter(title__icontains=request.GET.get('term'))
titles = list()
for product in qs:
titles.append(product.title)
# titles = [product.title for product in qs]
return JsonResponse(titles, safe=False)
return render(request, 'file_for_viewing.html')
Run Code Online (Sandbox Code Playgroud)
然后这是网址:
path('autocomplete',views.autocomplete, name='autocomplete'),
Run Code Online (Sandbox Code Playgroud)
即使源是列表,自动完成功能也不起作用:
source: '['chicago', …Run Code Online (Sandbox Code Playgroud) pip3 install django-cors-headers
Requirement already satisfied: django-cors-headers in /usr/local/lib/python3.6/site-packages
You are using pip version 9.0.1, however version 9.0.3 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Run Code Online (Sandbox Code Playgroud)
我已经运行了以下命令:
然后我将它设置在我的 INSTALLED_APPS 中,如下所示:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders'
]
Run Code Online (Sandbox Code Playgroud)
然后我像这样在中间件中使用它,
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware'
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
ModuleNotFoundError: No module named 'corsheaders.middleware.CorsMiddlewaredjango'; 'corsheaders.middleware' is not a package
The above exception was the direct cause of the …Run Code Online (Sandbox Code Playgroud) 我试图重写在Angular 2中可以正常工作的服务,并且试图重写Angular 6。
这是服务:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';
import {Cluster} from "./cluster";
import {map} from "rxjs/internal/operators";
@Injectable({
providedIn: 'root'
})
export class FullDataService {
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: HttpClient) {}
getClusters() {
const url = environment.apiUrl + '/api/v1/clusters';
return this.http.get(url).pipe(map(res => <Cluster[]>res));
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的app.models.ts:
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { NgModule …Run Code Online (Sandbox Code Playgroud) django ×6
python ×3
cors ×2
javascript ×2
reactjs ×2
angular ×1
autocomplete ×1
cross-domain ×1
jquery ×1
overpass-api ×1
python-3.9 ×1