最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Api call using fetch with method get - Stack Overflow

programmeradmin2浏览0评论

I have to set an header in api call. My POST API calls are working fine. But in my get api calls, header is not getting set.

return fetch('', {
  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);
});

I have to set an header in api call. My POST API calls are working fine. But in my get api calls, header is not getting set.

return fetch('http://api-call.', {
  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);
});
Share Improve this question edited Apr 28, 2018 at 11:33 Sadhu asked Apr 28, 2018 at 11:03 SadhuSadhu 8903 gold badges9 silver badges18 bronze badges 3
  • add code snippet – BugHunter Commented Apr 28, 2018 at 11:04
  • And write a properly detailed problem description. Details provided are far too vague. Take a few minutes to read How to Ask and minimal reproducible example – charlietfl Commented Apr 28, 2018 at 11:18
  • @BugHunter - Edited my question.. – Sadhu Commented Apr 28, 2018 at 11:34
Add a ment  | 

2 Answers 2

Reset to default 4

You should setup a Request object and pass your headers wrapped into a Headers object, like:

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

Then just invoke fetch with your request as parameter:

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

Check reference

2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as pared to axios.

I'm using jsonplaceholder fake API to demonstrate:

Fetch api GET request using async/await:

         const asyncGetCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode./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()

Fetch api POST request using async/await:

    const asyncPostCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode./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()

GET request using Promises:

  fetch('https://jsonplaceholder.typicode./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)
  })

POST request using Promises:

fetch('https://jsonplaceholder.typicode./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)
  })  

GET request using Axios:

        const axiosGetCall = async () => {
            try {
              const { data } = await axios.get('https://jsonplaceholder.typicode./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()

Authenticated POST request using Axios:

const axiosPostCall = async () => {
    try {
      const { data } = await axios.post('https://jsonplaceholder.typicode./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()
发布评论

评论列表(0)

  1. 暂无评论