【问题标题】:Axios request failing for localhost, but working when I specify its IP本地主机的 Axios 请求失败,但在我指定其 IP 时工作
【发布时间】:2022-01-09 11:09:24
【问题描述】:

我最近为我的 Node 项目获得了一个 AWS Lightsail 实例,我的数据库和 Node 项目都在此服务器上运行。

但是,我在 NextJS 中有一个内置 API,我在客户端页面中调用它。对localhost 的 GET 请求可以正常工作,但每当我向localhost 发帖时,我都会收到Network Error

当我将 IP 从服务器更改为静态 IP 时,它工作得很好。我需要使用localhost,以便我可以在其他机器上开发(和运行)该项目。这是我的代码:

    axios
      .post<post>("http://localhost:3000/api/posts", post, {
        headers,
        withCredentials: true
      })
      .then(post => {
        window.location.reload();
      })
      .catch(async error => {
        console.error("AXIOS ERROR:");
        console.error(await error);
      })

正如我所说,当我将 localhost 更改为服务器运行的 IP 时,它工作得很好。我该如何解决这个问题?

【问题讨论】:

  • 很可能是 CORS 问题。您的本地主机服务器在什么上运行? express.js?
  • 您确定您的后端在 3000 端口上,而不是在 8000 之类的端口上吗?

标签: typescript axios debian


【解决方案1】:

答案是一起删除IP:

    axios
      .post<post>("http://localhost:3000/api/posts", post, {
        headers,
        withCredentials: true
      })
      .then(post => {
        window.location.reload();
      })
      .catch(async error => {
        console.error("AXIOS ERROR:");
        console.error(await error);
      })

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2019-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 2020-02-28
  • 2019-04-30
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多