You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django+React项目中Axios请求返回HTML而非JSON数据问题

问题:Axios请求DRF接口返回React/Vite HTML而非JSON数据

我使用Django Rest Framework和React开发Web应用,当通过Axios向http://localhost:8000/api/v1/auth/users/daniel/请求用户资料时,接口未返回预期的用户JSON数据,反而返回了React/Vite的HTML代码。

返回的HTML内容

<!doctype html>
<html lang="en">
  <head>
    <script type="module">
import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>

    <script type="module" src="/@vite/client"></script>

    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx?t=1717529669140"></script>
  </body>
</html>

预期结果

我预期获取DRF返回的用户资料JSON数据。

相关代码

urls.py

urlpatterns = [
    .....,
    path('api/v1/auth/users/<str:username>/', views.UserProfileByUsernameView.as_view(), name='user-profile-by-username'),
]

views.py

class UserProfileByUsernameView(APIView):
    permission_classes = [AllowAny]

    def get(self, request, username):
        user = get_object_or_404(User, username=username)
        profile_serializer = UserProfileSerializer(user.userprofile)
        
        profile_data = profile_serializer.data
        profile_data['username'] = user.username
        profile_data['email'] = user.email

        return Response(profile_data, status=status.HTTP_200_OK)

serializers.py

class UserProfileSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True)
    email = serializers.EmailField(source='user.email', read_only=True)
    
    class Meta:
        model = UserProfile
        fields = '__all__'

profile-page.jsx

const ProfilePage = () => {
  const { username } = useParams();
  const [userProfile, setUserProfile] = useState(null);
  const [isOwnProfile, setIsOwnProfile] = useState(false);
  const loggedInUsername = localStorage.getItem('username');

  useEffect(() => {
    const fetchUserProfile = async () => {
      try {
        const response = await axios.get(`/api/v1/auth/users/${username}/`, {
          headers: {
            'Authorization': `Bearer ${userToken()}`,
          },
        });
        console.log(response)
        setUserProfile(response.data);
        setIsOwnProfile(loggedInUsername === username);
      } catch (error) {
        console.error('Error fetching user profile:', error);
      }
    };

    fetchUserProfile();
  }, [username, loggedInUsername]);

  console.log(userProfile);

  if (!userProfile) {
    return (
      <div className="flex justify-center items-center h-screen">
        <div className="text-lg font-semibold">Loading...</div>
      </div>
    );
  }
}

已尝试的解决方法

我已尝试通过开发者工具排查、简化返回模型、清除缓存等方法,但均未解决问题。


内容的提问来源于stack exchange,提问作者daniellambert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 22:55:14