Tengo un objeto api configurado de esta manera en reaccionar nativo:
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;Al hacer la llamada a la API estoy haciendo esto:
await myApi .get("/routeHere", { latitude: currentLocation.latitude, longitude: currentLocation.longitude, }) .then((response) => console.log(response)) .catch((err) => console.log(err));Al recibir los datos, la parte del cuerpo es solo un objeto vacío. ¿Hay alguna razón por la que esto sucede? ¿Estoy haciendo algo mal?
router.get("/routeHere", async (req, res) => { console.log("here is my body: ", req.body); }Creo que me falta agregar el tipo de encabezado, pero no estoy seguro de si funcionará, y si es así, ¿cómo puedes escribirlo? soy nuevo en expresar y reaccionar nativo
La solicitud GET no debe incluir datos.
El método HTTP GET solicita una representación del recurso especificado. Las solicitudes que usan GET solo deben usarse para solicitar datos (no deben incluir datos).
Pero puedes usar params para enviar la latitud y la longitud, así:
await myApi .get(`/routeHere?latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}`) .then((response) => console.log(response)) .catch((err) => console.log(err));o
await myApi .get("/routeHere", { params: { latitude: currentLocation.latitude, longitude: currentLocation.longitude, } }) .then((response) => console.log(response)) .catch((err) => console.log(err)); Y puede recibirlo en el backend con req.query.latitude y req.query.longitude