【问题标题】:Problem with getting data with Fetch - JavaScript使用 Fetch 获取数据的问题 - JavaScript
【发布时间】:2021-01-21 21:40:22
【问题描述】:

通过Postman 程序,我使用GEThttps://lit-brushlands-92375.herokuapp.com/api/items 下载我的购物清单

我想在浏览器控制台或带有代码的网站上做同样的事情:

fetch('https://lit-brushlands-92375.herokuapp.com/api/items')
  .then(response => response.json())
  .then(data => console.log(data));

返回如下错误

VM89: 1 GET https://lit-brushlands-92375.herokuapp.com/api/items 网络 :: ERR_FAILED

我做错了什么?有什么可以做得更好?

【问题讨论】:

    标签: javascript reactjs express heroku fetch


    【解决方案1】:
    fetch('https://lit-brushlands-92375.herokuapp.com/api/items')
      .then(function(response) {
        return response.json();
      }).then(function(data) {
        console.log(data);
      });
    

    为我工作得很好!如果你希望它更干净,可以这样写。

    fetch('https://lit-brushlands-92375.herokuapp.com/api/items').then((response)=>response.json()).then((data) =>console.log(data));
    

    【讨论】:

    • 也许你修好了,但没有问题?
    【解决方案2】:

    前端和后端都在 Heroku 上。我收到了 CORS 错误。我在后端层的主文件中添加了如下代码:

    app.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader(
          'Access-Control-Allow-Headers',
          'Origin, X-Requested-With, Content-Type, Accept, Authorization'
        );
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
      
        next();
      });
    

    多亏了这个,我以下载数据的形式获得了满意的效果。

    【讨论】:

      猜你喜欢
      • 2018-09-29
      • 2020-06-29
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2021-02-02
      • 2017-12-14
      • 2017-03-06
      • 2018-07-20
      相关资源
      最近更新 更多