【问题标题】:404 Failed to load resource: the server responded with a status of 404 (Not Found) Django React404 Failed to load resource: 服务器响应状态为 404 (Not Found) Django React
【发布时间】:2020-08-05 17:56:03
【问题描述】:

我正在尝试让 React 通过 React DropZone 上传图像。但是,当我转到我的博客管理器页面时,控制台会立即记录 404 Failed to load resource:服务器响应状态为 404(未找到)。我在后端使用 Django Rest Framework,在终端中显示“GET /media/Upload%20image HTTP/1.1”。前端 react 可以获取页面上的图片文件,但是不会上传。

这是后端 DRF 中的 settings.py:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'p%s-9w1l268@!b$p#92dj26q)pv7!&ln^3m(1j5#!k8pkc9@(u'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    # 'allauth',
    # 'allauth.account',
    # 'allauth.socialaccount',
    'corsheaders',
    # 'rest_auth',
    # 'rest_auth.registration',
    'rest_framework',
    # 'rest_framework.authtoken',

    'menus',
    'phlogfeeder',
    'login'
]

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',
]

ROOT_URLCONF = 'chefsBackEnd.urls'

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 = 'chefsBackEnd.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.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'},
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

这是我的静态文件设置所在的位置:

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

STATIC_URL = '/static/'


STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'build/static'),
]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# STATICFILES_FINDERS = [
#     'django.contrib.staticfiles.finders.FileSystemFinder',
#     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# ]

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')


# SITE_ID = 1

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework.authentication.TokenAuthentication',
        # 'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',

        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )

}

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True


CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000'
]

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

JWT_AUTH = {
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'chefsBackEnd.utils.resp_handler',

    # 'JWT_ENCODE_HANDLER':
    # 'rest_framework_jwt.utils.jwt_encode_handler',

    # 'JWT_DECODE_HANDLER':
    # 'rest_framework_jwt.utils.jwt_decode_handler',

    # 'JWT_PAYLOAD_HANDLER':
    # 'rest_framework_jwt.utils.jwt_payload_handler',

    # 'JWT_PAYLOAD_GET_USER_ID_HANDLER':
    # 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    'JWT_ALGORITHM': 'HS256',
    'JWT_VERIFY': True,

}

我的 urls.py 文件:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from rest_framework_jwt.views import obtain_jwt_token
from rest_framework_jwt.views import verify_jwt_token

urlpatterns = [
    path('api-auth/', include('rest_framework.urls')),
    path('rest-auth/', include('rest_auth.urls')),
    # path('rest-auth/registration/', include('rest_auth.registration.urls')),
    path('token-auth/', obtain_jwt_token),
    path('api-token-verify/', verify_jwt_token),
    path('login/', include('login.urls')),
    path('admin/', admin.site.urls),
    path('api/', include('menus.api.urls')),
    path('phlogapi/', include('phlogfeeder.phlogapi.urls'))
]

在这里我添加了 url 模式以提供对静态和媒体文件的访问

if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

控制台一直说upload/%20/media。

前端: phlogEditor.js

import React, { Component } from 'react';
import axios from 'axios';
import DropzoneComponent from 'react-dropzone-component';

import "../../../node_modules/react-dropzone-component/styles/filepicker.css";
import "../../../node_modules/dropzone/dist/min/dropzone.min.css";

class PhlogEditor extends Component {
    constructor(props) {
        super(props);

        this.state = {
            id: '',
            phlog_status: '',
            phlog_image: '',
            editMode: false,
            position: '',
            apiUrl: 'http://127.0.0.1:8000/phlogapi/phlog/create/',
            apiAction: 'post'
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.componentConfig = this.componentConfig.bind(this);
        this.djsConfig = this.djsConfig.bind(this);
        this.handlePhlogImageDrop = this.handlePhlogImageDrop.bind(this);
        this.deleteImage = this.deleteImage.bind(this);

        this.phlogImageRef = React.createRef();
    }

    deleteImage(event) {
        event.preventDefault();
        axios
            .delete(
                `http://127.0.0.1:8000/phlogapi/phlog/${this.props.id}/delete`,
                { withCredentials: true }
            )
            .then(response => {
                this.props.handlePhlogImageDelete();
            })
            .catch(error => {
                console.log('deleteImage failed', error)
        });
    }

    componentDidUpdate() {
        if (Object.keys(this.props.phlogToEdit).length > 0) {
            const {
                id,
                phlog_image,
                phlog_status,
                position
            } = this.props.phlogToEdit;

            this.props.clearPhlogsToEdit();

            this.setState({
                id: id,
                phlog_image: phlog_image || '',
                phlog_status: phlog_status || '',
                position: position || '',
                editMode: true,
                apiUrl: `http://127.0.0.1:8000/phlogapi/phlog/${this.props.id}/update`,
                apiAction: 'patch'
            });
        } 
    }

    handlePhlogImageDrop() {
        return {
            addedfile: file => this.setState({ phlog_image: file })
        };
    }


    componentConfig() {
        return {
          iconFiletypes: [".jpg", ".png"],
          showFiletypeIcon: true,
          postUrl: "https://httpbin.org/post"
        };
    }

    djsConfig() {
        return {
          addRemoveLinks: true,
          maxFiles: 3
        };
    }

    buildForm() {
        let formData = new FormData();

        formData.append('phlog[phlog_status]', this.state.phlog_status);
        formData.append('phlog[position]', this.state.position);

        if (this.state.phlog_image) {
            formData.append(
                'phlog[phlog_image]',
                this.state.phlog_image
            );
        }

        return formData;
    }


    handleChange(event) {
        this.setState({
          [event.target.name]: event.target.value
        });
    }

    handleSubmit(event) {
        axios({
            method: this.state.apiAction,
            url: this.state.apiUrl,
            data: this.buildForm(),
            withCredentials: true
        })
        .then(response => {

            if (this.state.editMode) {
                this.props.handlePhlogSubmission();
            } else {
                this.props.handleNewPhlogSubmission(response.data);

            }

            this.setState({
                phlog_status: '',
                phlog_image: '',
                position: '',
                editMode: false,
                apiUrl:'http://127.0.0.1:8000/phlogapi/phlog/create/', 
                apiAction: 'post'
            });

            [this.phlogImageRef].forEach(ref => {
                ref.current.dropzone.removeAllFiles();
            });
        })
        .catch(error => {
            console.log('handleSubmit phlogEditor error', error);
        });

       event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit} className='phlog-editor-wrapper'>
                <div className='two-column'>
                    <input
                        type='text'
                        name='position'
                        placeholder='Position'
                        value={this.state.position}
                        onChange={this.handleChange}
                    />

                    <select
                        name='phlog status'
                        value={this.state.phlog_status}
                        onChange={this.handleChange}
                        className='select-element'
                    >
                        <option value='Draft'>Draft</option>
                        <option value='Published'>Published</option>
                    </select>
                </div>

                <div className='image-uploaders'>
                    {this.state.editMode && this.state.phlog_image_url ? (
                        <div className='phlog-manager-image-wrapper'>
                            <img src={this.state.phlog_image_url} />

                        <div className='remove-image-link'>
                            <a onClick={() => this.deleteImage('phlog_image')}>
                                Remove Photos
                            </a>
                        </div>
                    </div>
                ) : (
                    <DropzoneComponent
                        ref={this.phlogImageRef}
                        config={this.componentConfig()}
                        djsConfig={this.djsConfig()}
                        eventHandlers={this.handlePhlogImageDrop()}
                    >
                        <div className='phlog-msg'>Phlog Photo</div>
                    </DropzoneComponent>
                )}
                </div>
                    <button className='btn' type='submit'>Save</button>
            </form>
        );
    }
}

export default PhlogEditor;

【问题讨论】:

    标签: django reactjs django-rest-framework


    【解决方案1】:

    将 Build 文件夹添加到 settings.py 文件中的 INSTALLED_APPS 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-13
      • 2018-06-08
      • 2021-07-22
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多