【问题标题】:Axios get request from local server url from within React appAxios 从 React 应用程序中获取本地服务器 url 的请求
【发布时间】:2021-01-07 00:31:12
【问题描述】:

我有一个带有 API 路由的 Typescript Express 服务器,它还为域根目录上的 Typescript React 应用程序提供服务。 例如

  • https://myapp.test 返回 React Web 应用
  • https://myapp.test/api/message 返回一些消息字符串

在 React 应用程序内部,我使用 axios 向 API 路由发送 GET 请求并获取消息:

function App() {
    const [data, setData] = useState("");
    useEffect( () => {
        ( async () => {
            const message = (await axios("http://localhost:8000/api/message")).data as string;
            setData(message);
        })();    
    }, []); 
  return (
      <div>Message is: {data}</div>
  );
}

我可以提供相对于当前 URL 的请求 URL 吗?例如,"/api/message" 之类的东西。如果没有,我应该如何配置 React 以便它能够可靠地知道 API url,而不管它部署在哪里(例如 Heroku)?

【问题讨论】:

    标签: reactjs express url get axios


    【解决方案1】:
              const message = (await 
              axios(window.location.host+"/api/message")).data as string;
    

    【讨论】:

      猜你喜欢
      • 2018-03-11
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 2020-04-17
      • 2023-01-31
      相关资源
      最近更新 更多