【问题标题】:I am getting error when I fetch Data from my backend?从后端获取数据时出现错误?
【发布时间】:2020-09-15 02:09:18
【问题描述】:

我正在使用 expressjs 在“http://localhost:3001/”上运行我的后端

app.listen(3001, function() {
    console.log('Server is running');
});

我在“http://localhost:3000/”上使用 react 的前端,但是当我获取数据时出现错误

package.json
    "proxy": "http://localhost:3001",

componentDidMount() {
        const fetchData = async () => {
            fetch('/data')
                .then(res => res.json())
                .then(d => console.log(d));
        };
        fetchData();
    }

here is the error

【问题讨论】:

  • 你可以复制/粘贴文本中的错误而不是使用屏幕截图吗?并且代理配置使用 localhost:8000 但你的 nodejs 监听 localhost:3001
  • 查看浏览器的开发者工具的网络选项卡。检查该请求得到了什么作为响应。
  • 正在发送请求到localhost:3000/data,但它应该是localhost:3001/data

标签: javascript reactjs express


【解决方案1】:

您在客户端的 package.json 文件中的代理应设置为您在后端尝试连接的任何服务器:

package.json
    "proxy": "http://localhost:3001",

【讨论】:

  • 对不起,我在 3001 有它
  • 您必须从控制台复制粘贴错误,以便我提供更多帮助
【解决方案2】:

“/data”路由是否存在?

如果没有,您正在尝试从 html 文件中提取 JSON,因此会出现错误。 删除.then(res => res.json()),直到您在服务器上定义路由。

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2021-08-17
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    相关资源
    最近更新 更多