我有一个 React 应用程序,当前位于 localhost 3000 上。服务器端由 Node Express 应用程序处理,该应用程序当前正在监听 localhost 3001。
当我运行 npm start 时,我同时启动这两个。 我在下面的 useEffect 代码中意识到,我无法相对设置 Express 应用程序的路径(用 axious 调用,因为当我在 React 应用程序(localhost 3000)上时,我的 Express 应用程序在 3001 上运行。我想知道如何将其实现为相对路径,展望未来,当我需要部署此应用程序时,我相信这将是我会遇到问题的情况,谢谢。
useEffect(() => {
console.log("this is our use effect function")
//we can make our async function here
//we can call the user favourites in the db to populate our recipes
//we can also call the db to populate the items in this users fridge.
//we store our token in the local storage.
async function getUser(){
let res = await axios.get("http://localhost:3001/users/testuser")
console.log(res.data)
}
getUser()
},[])
这可以借助 axios 配置默认值来实现。您不需要指定完整的 url,而只需指定需要为您提供响应的特定端点。
//axiosConfig.js
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3001';
export default axios;
您还可以添加通用标头,并可以使用
axios-interceptors
处理响应。请参阅axiosDocs。
import axios from "./axiosConfig.js"; // path to your axiosConfig file
useEffect(() => {
async function getUser(){
let res = await axios.get("/users/testuser", {}); //you can hit the particular end point that you need
console.log(res.data);
}
getUser();
},[])
请记住,无论您在哪里使用 axios,都需要从 axiosConfig.js 文件导入 axios。