为什么路由正确但在 Django 上仍然给出 404 错误

Why is the route correct but still giving 404 error on Django

我的网站在访问正确的路由时出现404错误,我是不是做错了什么

urls.py处​​理主干道

from django.contrib import admin
from django.urls import path,include,re_path
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'api/facebook/(.+?)', include('apifacebooks.urls')),
    path('', include('app.urls')),
    path('getcookie', include('app.urls')),
    path('change-lang', include('app.urls')),
    re_path(r'auth/(.+?)', include('app.urls')),
]

urls.py 在 apifacebooks 应用程序中处理路由

from django.urls import path
from . import views

urlpatterns = [
    path('api/facebook/like-post',views.like_post)
]

当我转到 http://localhost:8000/api/facebook/like-post 时出现 404 错误

Image error 404

我的问题已经解决了,谢谢

在您的 apifacebooks 应用程序中更改路径,因为路径中有两个“api...”


from django.urls import path
from . import views

urlpatterns = [
    path('like-post/',views.like_post)
]

而在根 urls.py 中

path('api/facebook/', ....)

在您的代码中,url 模式将是“http://localhost:8000/api/facebook/api/facebook/like-post”。 正如所解释的 id Django docs:

Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

去掉“apifacebooks.urls”中的“api/facebook/”,例如:

主要urls.py

from django.contrib import admin
from django.urls import path,include,re_path
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'api/facebook/(.+?)/', include('apifacebooks.urls')),
    path('', include('app.urls')),
    path('getcookie', include('app.urls')),
    path('change-lang', include('app.urls')),
    re_path(r'auth/(.+?)', include('app.urls')),
]

apifacebooks.urls

from django.urls import path
from . import views

urlpatterns = [
    path('like-post',views.like_post)
]

或者你可以尝试放置 remove "r'api/facebook/(.+?)'",例如:

from django.contrib import admin
from django.urls import path,include,re_path
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('apifacebooks.urls')),
    path('', include('app.urls')),
    path('getcookie', include('app.urls')),
    path('change-lang', include('app.urls')),
    re_path(r'auth/(.+?)', include('app.urls')),
]