admin管理员组

文章数量:1404936

I'm trying to implement an authentication system and stack on the register part

When I submit the form data I get back this error:

POST http://127.0.0.1:8000/api/register/ 404 (Not Found)

Here is some of my code

url.py
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from .views import RegisterView, LoginView, RefreshTokenView

urlpatterns = [
    path("api/register/", RegisterView.as_view(), name="register"),
    path("api/login/", LoginView.as_view(), name="login"),
    path("api/token/refresh/", RefreshTokenView.as_view(), name="token_refresh"),
]
view.py
class RegisterView(APIView):
    permissions_classes = [AllowAny]
    
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            return Response({"message": "User registered succefully"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

On the client side; I have a utility that creates the baseURl

import axios from "axios";

const API = axios.create({
    baseURL: "http://127.0.0.1:8000/api/",
    headers: {
        "Content-Type": "application/json",
    }
});

export default API;

And my handleSubmit function looks like this;

const handleSubmit = async (e) => {
    e.preventDefault();
    setError(""); // Clear previous errors

    try {
        const endpoint = isSignup ? "register/" : "login/";
        const response = await API.post(endpoint, formData);

        if (isSignup) {
            alert("Registration successful!");
            setIsSignup(false); // Switch to login form
        } else {
            // Store JWT tokens
            localStorage.setItem("accessToken", response.data.access);
            localStorage.setItem("refreshToken", response.data.refresh);
            localStorage.setItem("role", response.data.role);

            console.log("Login successful:", response.data);
            alert("Login successful!");

            const roleRedirects = {
                "admin": "/admin-dashboard",
                "student": "/student-dashboard",
                "lecturer": "/lecturer-dashboard",
                "academic_registrar": "/registrar-dashboard"
            };

            window.location.href = roleRedirects[response.data.role] || "/dashboard";
        }
    } catch (error) {
        setError(error.response?.data?.error || "Something went wrong. Please try again.");
        console.error("Error:", error);
    }
};


I need as much help as you could give

I'm trying to implement an authentication system and stack on the register part

When I submit the form data I get back this error:

POST http://127.0.0.1:8000/api/register/ 404 (Not Found)

Here is some of my code

url.py
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from .views import RegisterView, LoginView, RefreshTokenView

urlpatterns = [
    path("api/register/", RegisterView.as_view(), name="register"),
    path("api/login/", LoginView.as_view(), name="login"),
    path("api/token/refresh/", RefreshTokenView.as_view(), name="token_refresh"),
]
view.py
class RegisterView(APIView):
    permissions_classes = [AllowAny]
    
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            return Response({"message": "User registered succefully"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

On the client side; I have a utility that creates the baseURl

import axios from "axios";

const API = axios.create({
    baseURL: "http://127.0.0.1:8000/api/",
    headers: {
        "Content-Type": "application/json",
    }
});

export default API;

And my handleSubmit function looks like this;

const handleSubmit = async (e) => {
    e.preventDefault();
    setError(""); // Clear previous errors

    try {
        const endpoint = isSignup ? "register/" : "login/";
        const response = await API.post(endpoint, formData);

        if (isSignup) {
            alert("Registration successful!");
            setIsSignup(false); // Switch to login form
        } else {
            // Store JWT tokens
            localStorage.setItem("accessToken", response.data.access);
            localStorage.setItem("refreshToken", response.data.refresh);
            localStorage.setItem("role", response.data.role);

            console.log("Login successful:", response.data);
            alert("Login successful!");

            const roleRedirects = {
                "admin": "/admin-dashboard",
                "student": "/student-dashboard",
                "lecturer": "/lecturer-dashboard",
                "academic_registrar": "/registrar-dashboard"
            };

            window.location.href = roleRedirects[response.data.role] || "/dashboard";
        }
    } catch (error) {
        setError(error.response?.data?.error || "Something went wrong. Please try again.");
        console.error("Error:", error);
    }
};


I need as much help as you could give

Share Improve this question asked Mar 9 at 14:55 BakerBaker 33 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

You should fix the typo in RegisterView.

permissions_classes = [AllowAny]  # ❌ Incorrect

permission_classes = [AllowAny]  # ✅ Correct

Have Your tried requesting this endpoint in postman? If the issue persists in postman then the problem is in your backend code and endpoints. If postman process request successfully then your frontend is not picking that url. For that purpose you have to expose/forward your django port with ngrok

ngrok http 8000

Then give that ngrok public url in frontend

For example if ngrok gave you url: https://dehde-343-hdcnd-324n/ -> 8000 then in frontend replace "http://127.0.0.1:8000" with "https://dehde-343-hdcnd-324n/"

It will solve your problem but if the issue still persists then try following:

For testing purpose, give your whole backend signup url to baseUrl of API like this:

const API = axios.create({
    baseURL: "http://127.0.0.1:8000/api/register/",
    headers: {
        "Content-Type": "application/json",
    }
});

Also try to remove the last "/" from endpoint and test

http://127.0.0.1:8000/api/register

本文标签: reactjsAuthjsx38 POST http1270018000apiregister 404 (Not Found)DjangoReactStack Overflow