简体   繁体   English

Django 服务器和 React 前端项目上的 Cors 或 Axios 错误

[英]Cors or Axios Error on Django Server and React frontend project

When trying to connect my react component to the django server after installing corsheaders and adding it to installed apps in settings.py.在安装 corsheaders 并将其添加到 settings.py 中已安装的应用程序后尝试将我的反应组件连接到 django 服务器时。 I am still getting the following error:我仍然收到以下错误:

in goolge chrome: GET http://127.0.0.1:8000/api/teacher/ net::ERR_CONNECTION_REFUSED Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}在 goolge chrome 中:GET http://127.0.0.1:8000/api/teacher/net::ERR_CONNECTION_REFUSED未捕获(承诺)AxiosError {消息:'网络错误',名称:'AxiosError',代码:'ERR_NETWORK',配置:{…},请求:XMLHttpRequest,…}

In Firefox:在火狐中:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/teacher/ .跨域请求被阻止:同源策略不允许在http://127.0.0.1:8000/api/teacher/读取远程资源。 (Reason: CORS request did not succeed). (原因:CORS 请求未成功)。 Status code: (null).状态码:(空)。

I have already installed corsheaders and added it to my settings.py together with its middleware, and put allowed all cors origins in same file.我已经安装了 corsheaders 并将其与中间件一起添加到我的 settings.py 中,并将允许的所有 cors 来源放在同一个文件中。

I have also installed axios in react and put the import in my react component我还在 react 中安装了 axios 并将导入放入我的 react 组件中

Below is my settings.py code:下面是我的 settings.py 代码:

INSTALLED_APPS = [
    'main.apps.MainConfig',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]



TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Ateni_LMS_API.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases



# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

REST_FRAMEWORK={
    'DEFAULT_AUTHENTICATION_CLASSES':[
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        
    ],
}
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
ALLOWED_HOSTS = ['localhost', '127.0.0.1']

CORS_ALLOW_ALL_ORIGINS=True

Below is the relevant part of my react code:以下是我的反应代码的相关部分:

import React from "react";
import {useEffect, useState} from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useParams
} from "react-router-dom";
import axios from "axios";

const baseUrl='https://127.0.0.1:8000/api';
function PopularTeachers(){
    const [teacher,setTeacher] = useState(null);
    useEffect(()=>{
        axios.get(baseUrl+'/teacher/').then((response)=>{
            console.log(response.data);
        });
    },[]);

Given that you're running both servers locally there are 2 things you must make sure鉴于您在本地运行两台服务器,您必须确保两件事

  1. instead of python manage.py runserver do python manage.py runserver 0.0.0.0:8000而不是python manage.py runserverpython manage.py runserver 0.0.0.0:8000

  2. In your app.js replace https://127.0.0.1:8000/api with http://<your_ip>:8000/api You can get the ip address using ifconfig在您的 app.js 中,将https://127.0.0.1:8000/api替换为http://<your_ip>:8000/api您可以使用 ifconfig 获取 IP 地址

Other than this make sure whatever your ip address is, you add it to 'allowed hosts' in your settings.py file除此之外,请确保您的 IP 地址是什么,将其添加到 settings.py 文件中的“允许的主机”中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM