【问题标题】:Problem with fetch API while deploying MERN app to Heroku将 MERN 应用程序部署到 Heroku 时 fetch API 出现问题
【发布时间】:2020-03-28 21:58:16
【问题描述】:

我正在尝试在 Heroku 上部署一个 MERN 应用,但在获取 API 时遇到问题。以下代码在控制台中给出错误 "Uncaught (in promise) SyntaxError: Unexpected token E in JSON at position 0"

getDataFromDb = () => {
   fetch('https://product-listing-listing.herokuapp.com/api/getData')
      .then((data) => data.json())
      .then((res) => this.setState({ data: res.data }));
};

跳过根目录,只写fetch('/api/getData') 会出现同样的错误。

而当我使用 npm start 在本地运行应用程序并使用以下代码时,我没有收到任何错误:

getDataFromDb = () => {
   fetch('http://localhost:3001/api/getData')
      .then((data) => data.json())
      .then((res) => this.setState({ data: res.data }));
};

我做错了什么?

【问题讨论】:

  • 你看响应体是什么了吗?是 JSON 吗?请求是否成功 - 状态码是什么?

标签: node.js reactjs heroku fetch mern


【解决方案1】:

Uncaught (in promise) SyntaxError: Unexpected token E in JSON at position 0 表示fetch('https://product-listing-listing.herokuapp.com/api/getData') 返回一个无效的 JSON 结果。

试试

getDataFromDb = () => {
   fetch('https://product-listing-listing.herokuapp.com/api/getData')
      .then((data) => data.text())
      .then((res) => console.log(res));
};

检查fetch 返回的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2017-01-26
    • 2014-11-25
    • 2012-07-08
    • 2021-09-14
    • 2020-05-12
    • 1970-01-01
    相关资源
    最近更新 更多