I have a api object set up like this in react native:
import axios from "axios";
import AsyncStorage from "@react-native-async-storage/async-storage"; //npm install @react-native-async-storage/async-storage
const instance = axios.create({
baseURL: "localhost url here",
});
/**
* This will add a header if we have a token only,
* we will be adding a Authorization header to our instance before running
* the http req
*/
instance.interceptors.request.use(
//this will be called before doing the http request,
//it is async because to retrieve the storage it is async
async (config) => {
const token = await AsyncStorage.getItem("token"); //awaits until it gets token (IF THERE IS ONE)
//if there is a token
if (token) {
config.headers.Authorization = `Bearer ${token}`; //add string 'Bearer withGivenTOKEN'
}
return config;
},
(err) => {
return Promise.reject(err);
}
);
export default instance;
When doing the api call I am doing this:
await myApi
.get("/routeHere", {
latitude: currentLocation.latitude,
longitude: currentLocation.longitude,
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
When receiving the data the body part is just a an empty object. Is there a reason why this happens? Am I doing something wrong?
router.get("/routeHere", async (req, res) => {
console.log("here is my body: ", req.body);
}
I think I'm missing to add the header type, but not sure if it will work, and if it is, how can you write it? I'm new to express and react native
CodePudding user response:
GET request shouldn't include data.
The HTTP GET method requests a representation of the specified resource. Requests using GET should only be used to request data (they shouldn't include data).
But you can use params to send the latitude and the longitude, like this:
await myApi
.get(`/routeHere?latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}`)
.then((response) => console.log(response))
.catch((err) => console.log(err));
or
await myApi
.get("/routeHere", {
params: {
latitude: currentLocation.latitude,
longitude: currentLocation.longitude,
}
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
And you can receive it in the backend with req.query.latitude
and req.query.longitude