Mayuresh Patil
Mayuresh Patil

Reputation: 2200

How to pass JWT token through header in react native to django rest api?

I'm passing token(already i known from console) in header as in below code and want data from that localhost after that user get authenticated but on my android emulator it showing error Cannot convert undefined or null to object

Login.js

componentDidMount() {
     return fetch('http://10.42.0.1:8000/stocks/',
        {
         method: "GET",
         headers: 
         {
          'Authorization': `Bearer ${"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNhbSIsInVzZXJfaWQiOjYxLCJlbWFpbCI6IiIsImV4cCI6MTUwMzk0ODYyMH0.l4VLMLXcSZ7nOmKmjblLKFr0lTSpgYeFks_JeYiO7cU"}`
         }
  })

     ...

  }

In views.py

class Stocks(APIView):
      permissions_classes = [IsAuthenticated]
      authentication_classes= (TokenAuthentication,)
      def get(self,request):
          stocks=stock.objects.all()
          serailizer=serial(stocks,many=True)
          return Response(serailizer.data)

here the token is not reaching at the server and hence permission is not granted. we are using Django rest jwt token. Thank You

Upvotes: 2

Views: 1448

Answers (1)

mcmartin
mcmartin

Reputation: 106

The token format has been changed, now you need to send "JWT {token}" See the docs.

Then i recommend axios to 'organize' your server communication.

And the solution be like:

return axios({
  method: 'GET',
  url: `url`,
  headers: {
    Authorization: `JWT ${token}`,
  },
  data: dataToSend,
});

Upvotes: 3

Related Questions