【问题标题】:Getting a json from an api with fetch js使用 fetch js 从 api 获取 json
【发布时间】:2020-06-02 18:47:48
【问题描述】:

我只是不知道出了什么问题。我正在尝试使用 javascript 中的 fetch 从 api 获取 json。这是代码:

function get(){
      fetch('http://localhost:8082/marca/listar', {
            method: 'GET',
            headers: {},
            mode: 'no-cors', // <---
            cache: 'default'
        })
        .then(Response => { return Response.json() })
        .then(data => {
            console.log(data.nombre)
        });

}

This is the url of the api

我收到以下错误:

console message image

【问题讨论】:

  • 你能发布你遇到的错误吗?

标签: javascript api web get fetch


【解决方案1】:

每个https://developer.mozilla.org/en-US/docs/Web/API/Body/json你试过了吗:

response.json().then(data => {
  // do something with your data
});

【讨论】:

    【解决方案2】:

    这是因为你从服务器得到的响应是一个数组而不是 JSON 对象 所以就这样对待吧

    【讨论】:

      【解决方案3】:
      fetch('http://localhost:8082/marca/listar', 
      { cache: 'default' })
        .then(function (response) {
          if (response.status !== 200) {
            return;
          }
          response.json().then(function (data) {
            data.forEach((element) => {
              element.whatYouWant; /* Change (whatYouWant) to your desired output */
            })
          })
        })
        .catch(function (err) {
          console.log('Fetch Error :-S', err);
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-30
        • 2020-05-31
        • 1970-01-01
        • 2019-01-05
        • 2021-07-30
        • 1970-01-01
        • 2019-04-02
        • 1970-01-01
        相关资源
        最近更新 更多