Home > front end >  401 Error in React and django-rest-framework app
401 Error in React and django-rest-framework app

Time:03-14

First of all I got this useState which takes data from input:

const Checkout = ({cart, totalPrice, code}) => {
    const [values, setValues] = useState({
        email: '',
        city:'',
        adress:'',
        postalCode:'',
        phone:'',
        firstName:'',
        lastName:'',
        message:'',
        price: totalPrice,
        code: code,
        shipmentFee:0,
        shipmentMethod:'',
        lockerId:'',
        cart:cart,
    });

Then I submit it with generateOrder(values) function:

export const generateOrder = (order) => {
    return fetch(`${url}/orders/generate-bank-transfer-order/`,{
        method:"POST",
        body:order
    })
    .then((response) => {
        return response.json();
    })
    .catch((error) => console.log(error))
};

It points to this url in urls.py: path('generate-bank-transfer-order/',generate_bank_transfer_order, name="generate-bank-transfer")

And this is a view I use, for now I just want it to return submited data so I can test if it works:

@csrf_exempt
def generate_bank_transfer_order(request):
    if request.method == "POST":
        body = request.body
    return JsonResponse({"test":body})

All I get is 401 Unauthorized and I have no idea how to fix it. Any ideas?

CodePudding user response:

If you are using the default authentication class in settings like :

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

First import

from rest_framework.permissions import AllowAny

then modify your function to

@api_view(['POST'])
@permission_classes([AllowAny])
def generate_bank_transfer_order(request):
    if request.method == "POST":
        body = request.body
    return JsonResponse({"test":body})

For More Details

The AllowAny permission class will allow unrestricted access, regardless of if the request was authenticated or unauthenticated.

This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.

  • Related