【发布时间】:2026-02-21 16:10:01
【问题描述】:
我有一个后端 Django REST API,它也有助于为我的 React 前端提供服务。我目前在我的 API 请求 URL 路径到生产中的 Django API 时遇到问题,除了我的主页之外的每个页面......
有效的 API URL:
我能够访问我的主页,在我的主页中,我有一个对我的 API 的 GET 请求,它运行良好并按预期加载数据。这是我网站唯一有效的 GET 请求,因为 API URL 路径对我的urlpatterns 语法是正确的。
不起作用的 API URL:
当我访问我的 React 应用主页以外的页面时会出现问题。根据我的网络面板,我在其他页面上对 Django 的 API 请求使用了错误的 URL 路径(他们也以 index.html 响应),这让我相信我设置了我的 django URL 错误。
请在下面查看我的配置:
主 urls.py:
def render_react(request):
return render(request, "index.html") #<---- index.html from React
urlpatterns = [
path('auth/', include('drf_social_oauth2.urls', namespace='drf')),
path('admin/', admin.site.urls),
path('api/', include('bucket_api.urls', namespace='bucket_api')),
path('api/user/', include('users.urls', namespace='users')),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
urlpatterns += [
re_path('',render_react) #<---- Serving React index.html
]
这是一个问题示例:
当我访问这个子页面网址时:
https://mywebsite.com/try-demo/ra4r7n7mdb
一个 GET 请求也应该触发这个 URL:
https://mywebsite.com/api/demo/ra4r7n7mdb
但是,它不是将请求发送到上面的正确 URL,而是发送到这个 url:
https://mywebsite.com/try-demo/api/demo/ra4r7n7mdb
对于从我的 django api 请求数据的网站的其他部分来说,这也是同样的问题。因此,当我访问我的登录页面 (https://mywebsite.com/login) 并输入我的详细信息以请求身份验证令牌时。令牌的请求应该是:
https://mywebsite.com/auth/token/
但它通过以下方式请求数据:
https://mywebsite.com/login/auth/token/
如何解决这个问题?
我的 url 模式有一个捕获所有请求,然后我的反应能够处理 404 个不存在的页面。我唯一的问题是我的 React 应用程序如何在生产中向我的 API 请求数据。 (我主页上的 API 请求再次正常工作)为什么我的其他请求会附加我的 React 路由器 URL 的第一个 URL 路径?
我不想用代码阻塞这篇文章,所以请让我知道我应该在此处提供哪些其他信息来帮助解决这个问题?
更新
我已经解决了我的服务器的 API 请求问题。根据网络面板,路径现在是正确的。但是,问题仍然存在,我似乎只将我的 index.html 作为这些 API 请求的响应(它们应该是数据响应,而不是 index.html)
这是我为 Django 捕获的所有正则表达式
re_path(".*/", render_react),
re_path(r"^$", render_react)
新编辑
我现在可以让我的 API 数据请求之一以 JSON 数据进行响应(正如预期的那样) 这是有效的 API 请求的 URL:
https://mywebiste.com/api/demo/idoyem1l4k/
这些仍然不起作用:
https://mywebsite.com/api/demo/tabledata/idoyem1l4k
https://mywebsite.com/api/demo/graphdata/idoyem1l4k
我如何提出请求:
import axios from 'axios';
const baseURL = `https://mywebsite.com/api`;
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 9000,
headers: {
Authorization: 'Bearer ' + localStorage.getItem('access_token'),
'Content-Type': 'application/json',
accept: 'application/json',
},
});
export const getData = async (dispatch, slug, cancelToken) =>
{
try
{
console.log('fired demo request')
const response = await axiosInstance.get("demo/graphdata/" + slug, { cancelToken });
dispatch({ type: 'FETCH_SUCCESS', payload: response.data });
} catch (err)
{
if ('isCancel' in err && err.isCancel())
{
return;
}
dispatch({ type: 'FETCH_ERROR' });
}
}
如何返回请求的实际数据而不是我的索引?
【问题讨论】:
-
嘿,你能分享一下调用你的 api 的代码吗,因为那似乎是你的错误所在。
-
嗨@Klaassiek,所以我修复了我的API调用,URL路径现在是正确的。但是,他们总是在我的
urls.py中返回由render_react创建的index.html。请查看我更新的帖子,我已经修改了我如何配置我的 django 网址作为反应的全部内容。 -
源文件是开源的吗?我可能可以在我的机器上解决这个问题。
-
嘿 dacx,抱歉它不是开源的,但如果您需要我这边的更多信息,我很乐意提供。
-
根本原因可能是在发出请求的代码中,而不是在接受请求的 Django 部分,所以请显示发出调用的代码。
标签: reactjs django react-router axios react-router-dom