【问题标题】:Why I'm getting a POST http://localhost:3000/upload 404 (Not Found)?为什么我收到 POST http://localhost:3000/upload 404(未找到)?
【发布时间】:2021-07-18 21:48:56
【问题描述】:

我正在制作一个具有 React 前端和 Django 后端的项目。我正在为这个项目使用上传功能。用户可以从 React 前端上传文件,然后将这些文件上传到 Django 后端的媒体文件夹中。然后在 Django 后端处理文件,并将响应数据发送到 React 前端。

这是我的前端上传组件的代码。

import React,{useState} from 'react'
import './Upload.css'
import axios from 'axios'

export default function Upload() {

    const [selected,setSelected] = useState(null)
    const config = {headers:{"Content-Type":"multipart/form-data"}}



    const onChangeHandler=event=>{
        setSelected(event.target.files)
    }

    let url = 'http://127.0.0.1:8000/upload/';

    const onClickHandler = async () => {
        const data = new FormData()
        for(var x = 0; x<selected.length; x++) {
            data.append('file', selected[x])
        }

     try{
       const resp = await axios.post(url, data,config)
       console.log(resp.data)
    }
    catch(err){
        console.log(err.response)
    }
}
    

    return (
        <div className="upload-container">

            <form method="post" 
            encType="multipart/form-data"
            onSubmit={onClickHandler}
            >
    
            <input type="file" name="myfile" multiple onChange={onChangeHandler} />
            <input type="submit"  />
            </form>

        </div>
    )
}


这是 Django 后端的核心 urls.py 文件。 react 的上传组件有一个 '/upload' 的路由。因此,我在 URL 中创建了一个上传路径,该路径又链接到 Scanner.urls。 Scanner 是我在 Django 中创建的一个应用程序,上传的文件将被发布和处理。

from django.urls import path, include, re_path
from django.views.generic import TemplateView
urlpatterns = [
    path('auth/', include('djoser.urls')),
    path('auth/', include('djoser.urls.jwt')),
    path('upload/',include('Scanner.urls'))
]

urlpatterns += [re_path(r'^.*',TemplateView.as_view(template_name='index.html'))]

这是 Scanner 应用中的 urls.py 文件。

from django.urls import path, include, re_path
from django.views.generic import TemplateView
from . import views

urlpatterns = [
    path('',views.upload)
]


这是 Scanner 应用的 views.py 文件中的上传功能。除了上传函数之外,views.py 文件中还有其他辅助函数,用于在上传方法中处理文件。

@api_view(['POST','GET'])
@csrf_exempt
def upload(request):
    if request.method == 'POST':
        files = request.FILES.getlist('file')
        fs = FileSystemStorage()

        for file in files:
            if file and allowed_file(file.name):
                filename= file.name
                fs.save(file.name, file)
        target = os.path.join(APP_ROOT,'media/')
            

        data = ScanFiles(target)
        ext = data[1]
        mylist = data[0][0]

        for l in mylist:
            if l[1] != []:
                tup = VariablesData(l[1],ext)
                l[1] = []
                l[1].append(tup[0])
                l[1].append(tup[1])
                l[1].append(tup[2])

        for l in mylist:
            if l[2] != []:
                tup2 = MethodsData(l[2],ext)
                l[2] = []
                l[2].append(tup2[0])
                l[2].append(tup2[1])
                l[2].append(tup2[2])
                l[2].append(tup2[3])


        print(mylist)
        return Response(mylist,status=status.HTTP_200_OK)


So, when I post the files from the React frontend, I get this error.

While this is the error on the Django server. The gibberish above the error is just some data I've printed from files.

为什么会出现这些错误?文件上传到 django 服务器并进行处理,如 Django 后端中的 print 语句输出所示。但是,为什么我会收到这个错误以及为什么我能够将响应数据发送到 React 前端。请指导。

【问题讨论】:

  • 你能检查一下你的服务器端口吗?!在第二张图片中,端口 60760,您在代码中使用 8000,端口 3000 出现错误?!我认为这是相关的。
  • @AlaaM.Jaddou 我相信端口 60760 来自浏览器,端口 8000 是 Django 服务器,端口 3000 是 React。错误很可能正如我在下面描述的那样,因为没有阻止表单提交。
  • @AlaaM.Jaddou 我检查了这个。服务器启动时,它在端口 8000 上运行。但是,每次都会出现如图所示的错误,我每次都得到一个不同的端口。

标签: javascript python reactjs django axios


【解决方案1】:

您没有阻止提交表单,所以当您提交表单时,首先您的代码向 Django 服务器发出请求,然后继续向不允许 POST 请求的 React 前端发出请求网址。因此你会收到一个错误。

如何解决这个问题?只需在 onSubmit 处理程序中阻止表单提交:

const onClickHandler = async (e) => { // take the event as a parameter here
    e.preventDefault(); // Prevent form submission
    const data = new FormData()
    for(var x = 0; x<selected.length; x++) {
        data.append('file', selected[x])
    }
    try{
        const resp = await axios.post(url, data,config)
        console.log(resp.data)
    }
    catch(err){
        console.log(err.response)
    }
}

【讨论】:

  • 非常感谢,兄弟。我重新启动了应用程序。有效。你是救生员。
猜你喜欢
  • 2016-08-06
  • 2021-10-31
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 2015-11-04
相关资源
最近更新 更多