javascript - 使用数组参数获取 API GET 请求。如何?

标签 javascript fetch-api

为了摆脱 Ajax 调用,我更改了代码以使用 Javascript Fetch API非常干净。

在下面的示例中,我必须注释掉请求的 body 获取选项,并将 method 选项更改为 GET

我这样做是为了看看它是否有效,并且......它确实有效。

现在我想知道如何将 body 获取选项参数传递给请求。

最后,我遇到了一个名为 AbortController Interface 的问题。并且想知道您是否可以向我展示如何在下面的示例中实现它,或者它是否根本无法从中受益。

谢谢

// POST DATA
function postData(url = 'https://api.myjson.com/bins/elr1f', params = [{param1Key: 'param1Val'}]) {

  const fetchOptions = {
                    method: 'GET', // *GET, POST, PUT, DELETE, etc.
                    mode: 'cors', // no-cors, cors, *same-origin
                    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
                    credentials: 'same-origin', // include, *same-origin, omit
                    headers: {
                      // 'Content-Type': 'application/x-www-form-urlencoded',
                      'Content-Type': 'application/json',
                      // 'Content-Type', 'text/xml'
                    },
                    redirect: 'follow', // manual, *follow, error
                    referrer: 'no-referrer', // no-referrer, *client
                    // body:     JSON.stringify(params), // body data type must match "Content-Type" header
                };

  // Default fetchOptions are marked with *
    return fetch(url, fetchOptions)

    .then(function(response) {

      // RESPONSE VALIDATION
      switch (response.status) {
        case 200:
          // code...
          console.info('HTTP response status: 200 OK');
          return response;
          break;

        case 404:
          // code...
          throw new Error('HTTP response status: 404 Not Found.');
          break;

        case 500:
          // code...
          throw new Error('HTTP response status: 500 Internal Server Error.');
          break;

        case 503:
          // code...
          throw new Error('HTTP response status: 503 Service Unavailable.');
          break;
        
        default:
          // code...
          break;
      }
    
    })

    // parse JSON response into native JavaScript object(s) 
    .then (response => response.json() )
    // access the node we want
    .then (response => console.info(response.users) )
    // catch a freaking error
    .catch(error    => console.error(error) ); 
}
<button onclick="postData()">GET USERS</button>

最佳答案

GET 请求,只能在 URL 中指定参数,不应该有正文...

通过 POST 请求,您可以 supply parameters in the body. POST 请求的行为与 GET 请求类似,没有问题。

关于javascript - 使用数组参数获取 API GET 请求。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57661136/

相关文章:

javascript - Ajax 响应未定义

javascript - 在 React 中提交表单后无法清除输入字段

javascript - 如何链接多个 fetch() promise ?

javascript - css - 有没有办法让 div 与 h1(多行)在同一第二行?

javascript - 使用 Canvas 将文本添加到图像

javascript - 将键值对象转换为单个数组

JavaScript如何将Fetch数据存储到全局变量

javascript - 单击菜单项时关闭 jQuery 响应式菜单?

javascript - 使用 Node.js 获取本地文件

javascript - react js 获取 API