简体   繁体   中英

Jsonresponse in Django working in browser but not in PostMan or Angular

I am trying to send a JSON response from Django back-end to my angular front-end.

When I make the request I receive nothing in Postman or Angular but,opening the link in browser seems to be returning the correct result

My View is:

@api_view(['GET'])
def my_view(request):
    print(request.user.username)
    return JsonResponse({'username': request.user.username})

When I open http://127.0.0.1:8000/accounts/get_username/ in browser I receive {"username": "aditya8010"} on the web page. But when i do a get request using POSTMAN I recieve

{
    "username": ""
}

Same with Angular

this.http.get("http://127.0.0.1:8000/accounts/get_username/").subscribe((res) => {
      
      this.username = JSON.stringify(res["username"])
      console.log(this.username,"  ", res)
    })

this code also prints an empty username string.

Another thing I have noticed is that my print statement in the view does print anything random I put in there when called from POSTMAN or Browser but when I use request.user.username it doesnt print anything when called by POSTMAN. And each time the response code is 200

What am I doing wrong.

When you're sending the request you are not providing authentication credentials (ie something that identifies the user that is sending the request). How do you obtain this credentials?

You need to establish an authentication method. There are several but I recommend using Token authentication with knox package . Basically, you have an endpoint that logins the user with his username and password (normal json post request) and that endpoint returns a token. This token is what identifies the user. You send this token in the header of each request you need to be authenticated. That means you probably should include an IsAuthenticated permission for the view. In postman: 邮递员授权标头

API view:

from rest_framework.permissions import IsAuthenticated

@api_view(['GET'])
@authentication_classes([IsAuthenticated])
def my_view(request):
    print(request.user.username)
    return JsonResponse({'username': request.user.username})

When it is in a browser, your login information is remembered in the session. When using postman or Angular, you need to provide the user's information in the request header manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM