You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

1. Add CORS Support to Django (Core Fix)

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.py to enable the app and middleware (middleware order matters!):

    • Add corsheaders to INSTALLED_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 CorsMiddleware before CommonMiddleware in the MIDDLEWARE list:
      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 CORS configuration to the end of settings.py to 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
    
2. Fix the ALLOWED_HOSTS Warning

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 = True in settings.py and configure your proxy to pass the correct X-Forwarded-Host header. This way Django uses the proxy's host instead of the raw request port.
3. Adjust Your React Fetch Request

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"))
4. Verify the Fix

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:57:43