【问题标题】:How to access my React app with node backend in local network?如何在本地网络中使用节点后端访问我的 React 应用程序?
【发布时间】:2020-11-12 10:39:29
【问题描述】:

我在我的 MacBook 上创建了一个 react 应用程序,并使用 http://localhost:3000 访问它。 此外,我在http://localhost:5000 上运行了一个 nodejs express mysql 服务器。 当我在同一网络 (http://192.166.15.85:3000) 中的 Windows 10 笔记本电脑的浏览器中打开端口为 3000 的 IP 地址时,我看到了我的应用程序,但控制台为我的后端抛出了网络错误,因为它无法访问 http://localhost:5000 . 我在前端硬编码了axios.get() 以调用http://localhost:5000,这对我的MacBook 来说很好。但对于 Windows 10 笔记本电脑,我需要 IP 地址。 我该如何处理?

错误是:

GET http://localhost:5000/get_users net::ERR_CONNECTION_REFUSED
Error: Network Error
   at: createError(createError.js:16)
   at: XMLHttpRequest.handleError (xhr.js:91)

【问题讨论】:

  • 你能发布你得到的错误吗?我假设它链接到CORS
  • 我更新了问题。我认为它与 Windows 笔记本电脑上不存在的 localhost 相关联。当我用 ip 替换 localhost 时,它可以工作
  • 如果您尝试从您的 Windows 计算机访问后端,您需要将 localhost 替换为 ip 地址
  • 当然,并且知道问题:我该如何处理?
  • 是的,你是对的,你可以尝试用window.location.hostname做类似的事情

标签: javascript node.js reactjs networking


【解决方案1】:

可以通过window.location.hostname获取当前主机名,然后有条件地更改url

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-06
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2020-09-20
    相关资源
    最近更新 更多