【问题标题】:Api call using fetch with method get使用 fetch 和 get 方法调用 API
【发布时间】:2018-04-28 11:03:11
【问题描述】:

我必须在 api 调用中设置一个标头。我的 POST API 调用工作正常。但是在我的 get api 调用中,没有设置标头。

return fetch('http://api-call.com', {
  method: 'GET',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'custom-security':'XXXX',
    'Purchase-Code':'XXXXXXX',
    'Content-Type':'application/json',
    'Cache-Control':'max-age=640000'
  }
})
.then((response) => response.json())
.then((responseJson) => {
  console.log(responseJson);
})
.catch((error) => {
  console.error(error);
});

【问题讨论】:

标签: javascript reactjs react-native react-redux


【解决方案1】:

您应该设置一个Request 对象并将您的标头包装到Headers 对象中,例如:

var request = new Request('http://api-call.com', {
    method: 'GET',
    headers: new Headers({
       'Accept': 'application/json',
       'custom-security':'XXXX',
       'Purchase-Code':'XXXXXXX',
       'Content-Type':'application/json',
       'Cache-Control':'max-age=640000'
    })
});

然后只需使用您的 request 作为参数调用 fetch:

fetch(request)
    .then((response) => response.json())
    .then((responseJson) => {
        console.log(responseJson);
    })
    .catch((error) => {
        console.error(error);
    });

查看reference

【讨论】:

    【解决方案2】:

    2021 年回答:以防万一您在这里寻找如何使用 async/await 或 Promise 发出 GET 和 POST Fetch api 请求(与 axios 相比)。

    我用jsonplaceholder fake API来演示:

    使用 async/await 获取 api GET 请求:

             const asyncGetCall = async () => {
                try {
                    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
                     const data = await response.json();
                    // enter you logic when the fetch is successful
                     console.log(data);
                   } catch(error) {
                // enter your logic for when there is an error (ex. error toast)
                      console.log(error)
                     } 
                }
    
    
              asyncGetCall()
    

    使用 async/await 获取 api POST 请求:

        const asyncPostCall = async () => {
                try {
                    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
                     method: 'POST',
                     headers: {
                       'Content-Type': 'application/json'
                       },
                       body: JSON.stringify({
                 // your expected POST request payload goes here
                         title: "My post title",
                         body: "My post content."
                        })
                     });
                     const data = await response.json();
                  // enter you logic when the fetch is successful
                     console.log(data);
                   } catch(error) {
                 // enter your logic for when there is an error (ex. error toast)
    
                      console.log(error)
                     } 
                }
    
    asyncPostCall()
    

    使用 Promises 获取请求:

      fetch('https://jsonplaceholder.typicode.com/posts')
      .then(res => res.json())
      .then(data => {
       // enter you logic when the fetch is successful
        console.log(data)
      })
      .catch(error => {
        // enter your logic for when there is an error (ex. error toast)
       console.log(error)
      })
    

    使用 Promises 的 POST 请求:

    fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
       body: JSON.stringify({
         // your expected POST request payload goes here
          title: "My post title",
          body: "My post content."
          })
    })
      .then(res => res.json())
      .then(data => {
       // enter you logic when the fetch is successful
        console.log(data)
      })
      .catch(error => {
      // enter your logic for when there is an error (ex. error toast)
       console.log(error)
      })  
    

    使用 Axios 获取请求:

            const axiosGetCall = async () => {
                try {
                  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
        // enter you logic when the fetch is successful
                  console.log(`data: `, data)
               
                } catch (error) {
        // enter your logic for when there is an error (ex. error toast)
                  console.log(`error: `, error)
                }
              }
        
        axiosGetCall()
    

    使用 Axios 验证的 POST 请求:

    const axiosPostCall = async () => {
        try {
          const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts',  {
          // your expected POST request payload goes here
          title: "My post title",
          body: "My post content."
          },{
              headers: {
                   Authorization:
                `Bearer ${token}`
              }
             })
       // enter you logic when the fetch is successful
          console.log(`data: `, data)
       
        } catch (error) {
      // enter your logic for when there is an error (ex. error toast)
          console.log(`error: `, error)
        }
      }
    
    
    axiosPostCall()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-19
      • 2019-05-26
      • 1970-01-01
      • 2021-03-02
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      相关资源
      最近更新 更多