React.js前端向Django后端发请求时遇CORS及HTTP_HOST错误求助
Hey there, let's break down and fix your CORS and ALLOWED_HOSTS issues step by step. You're dealing with two linked problems here—Django's host validation warning and a failed CORS preflight request that's blocking your frontend from talking to the backend. Here's what to do:
Django doesn't handle cross-origin requests out of the box, so we'll use the standard django-cors-headers package to resolve the preflight OPTIONS error:
- First, install the package:
pip install django-cors-headers
Update your
settings.pyto enable the app and middleware (middleware order matters!):- Add
corsheaderstoINSTALLED_APPS:INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # Add this line ] - Insert
CorsMiddlewarebeforeCommonMiddlewarein theMIDDLEWARElist:MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', # Add this line first in the middleware stack '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', ]
- Add
Add CORS configuration to the end of
settings.pyto allow your frontend origin:# CORS Settings CORS_ALLOWED_ORIGINS = [ "http://XXX.XXX.XXX.XXX:55001", # Your React frontend URL "http://localhost:55001", # Optional: for local testing ] # Uncomment below if you need to allow all origins (only for development, not production!) # CORS_ALLOW_ALL_ORIGINS = True # Uncomment if your requests need to carry cookies # CORS_ALLOW_CREDENTIALS = True
You've added the IP to ALLOWED_HOSTS, but the warning mentions XXX.XXX.XXX.XXX:55002—Django's ALLOWED_HOSTS checks for hostnames without ports by default. Fix this in one of two ways:
- Option 1: Add the ported address to
ALLOWED_HOSTS:ALLOWED_HOSTS = ['XXX.XXX.XXX.XXX:55002', 'XXX.XXX.XXX.XXX', 'localhost', '127.0.0.1'] - Option 2 (Recommended for Production): If you're using a reverse proxy like Nginx, set
USE_X_FORWARDED_HOST = Trueinsettings.pyand configure your proxy to pass the correctX-Forwarded-Hostheader. This way Django uses the proxy's host instead of the raw request port.
Your GET request includes a Content-Type: application/json header, but GET requests don't have a request body—this can trigger unnecessary preflight checks or validation errors in Django. Remove the header:
fetch(url, { method: "GET", // Remove the Content-Type header for GET requests }) .then((resp) => resp.json()) .then((data) => this.updateDelay(data.prediction, data.probability)) .catch((error) => console.log(error, "catch the hoop"))
Restart your Django server, then test your frontend request:
- Check your browser console to confirm the CORS error is gone
- Look at Django's logs to ensure the ALLOWED_HOSTS warning no longer appears
内容的提问来源于stack exchange,提问作者ScalaBoy

