我有一个后端 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。
请在下面查看我的配置:
主要网址.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
]
以下是该问题的示例:当我访问此子页面 URL 时:
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
) 并输入我的详细信息以请求身份验证 token 时。对 token 的请求应该是:https://mywebsite.com/auth/token/
而是通过以下方式请求数据:https://mywebsite.com/login/auth/token/
如何解决这个问题? 我的 url 模式有一个捕获所有请求,然后我的 react 能够处理不存在的 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' });
}
}
如何返回请求的实际数据而不是我的索引?
最佳答案
这是有道理的,它总是返回 index.html。您捕获所有正则表达式会阻止调用您的 API 调用,因此它始终解析为 render_react
.我想你有3个选择。
re_path(".*/", render_react),
并不能涵盖所有内容并明确命名您要使用的每个 react 页面 re_path("(?!api).*/", render_react),
的内容排除您的 Django 应用程序。 我会选择选项 2,因为它可以让您最大程度地控制您的网址
关于reactjs - Django/React - 生产 API URL 路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67341738/