我在 react native 中設定了一個這樣的 api 物件:
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;
在進行 api 呼叫時,我正在這樣做:
await myApi
.get("/routeHere", {
latitude: currentLocation.latitude,
longitude: currentLocation.longitude,
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
接收資料時,正文部分只是一個空物件。發生這種情況有什么原因嗎?難道我做錯了什么?
router.get("/routeHere", async (req, res) => {
console.log("here is my body: ", req.body);
}
我想我缺少添加標題型別,但不確定它是否會起作用,如果是,你怎么寫?我是新來的表達和反應原生
uj5u.com熱心網友回復:
GET 請求不應包含資料。
HTTP GET 方法請求指定資源的表示。使用 GET 的請求只能用于請求資料(它們不應包含資料)。
獲取方法
但是您可以使用 params 發送緯度和經度,如下所示:
await myApi
.get(`/routeHere?latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}`)
.then((response) => console.log(response))
.catch((err) => console.log(err));
或者
await myApi
.get("/routeHere", {
params: {
latitude: currentLocation.latitude,
longitude: currentLocation.longitude,
}
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
你可以在后端接收req.query.latitude它req.query.longitude
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481707.html
標籤:javascript 节点.js 反应式 表示
