Matheus Melo
Matheus Melo

Reputation: 15

req.body undefined axios.get in react-native

I have this api.get which is axios.get in my react-native code, passing auth_token as param

const auth_token = await AsyncStorage.getItem('access_token');
api.get('/info/getallposts', {
      auth_token
})

auth_token is not null

on my back-end I have this decoder

let user_id = jwt.decode(req.body.auth_token).id;

req.body.auth_token is undefined

It works on POSTMAN :(

Upvotes: 0

Views: 141

Answers (1)

Julian
Julian

Reputation: 560

GET requests don't have a body associated with them. If you want to body-like args into a get request, you need to encode them in the URL using query parameters.

However, you don't want to do that with auth tokens. Instead, you're going to want to put the token in an http header. For JWT tokens, you'll probably want to use the Bearer Token header value.

try this:

const api = require('axios');

// make sure that this code is wrapped in an async function
const auth_token = await AsyncStorage.getItem('access_token');
const posts = await api.get('/info/getallposts', {
   headers: {
     Authorization: `Bearer ${auth_token}`
   }
})

Now in your backend code, you would need to look for "Authorization" key in the the headers field of the request object. Assuming you're using express, you're route would look something like this:

app.get('/info/getall/posts', (req, res) => {
  const authHeader = req.get('Authorization');
  const jwt = authHeader.split(' ')[0]; 
});

Of course I'd recommend making sure the header exists first before trying to split it... probably use middleware before it even executes the endpoint handler or something but this should get you going.

Upvotes: 1

Related Questions