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

javascript - How to convert axios to fetch? - Stack Overflow

programmeradmin4浏览0评论

I'm familiar with posting data with Axios, but trying to use fetch instead. How would I convert to a fetch request, I think what I'm doing is correct...

const data = new FormData();

The following axios request works:

data.append( 'Image', this.state.image, this.state.image.name );
axios.post( '/api/upload', data, {
    headers: {
        'accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.8',
        'Content-Type': 'multipart/form-data;',
    }
  })
   .then ...

I tried to convert here;

data.append( 'Image', this.state.image, this.state.image.name );
fetch( '/api/upload', data, {
    method: 'POST',
    headers: {
        'accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.8',
        'Content-Type': 'multipart/form-data;',
    },
    body: JSON.stringify(data)
  })
   .then ...

Returns 404 error, not found. What am I failing to do here?

I'm familiar with posting data with Axios, but trying to use fetch instead. How would I convert to a fetch request, I think what I'm doing is correct...

const data = new FormData();

The following axios request works:

data.append( 'Image', this.state.image, this.state.image.name );
axios.post( '/api/upload', data, {
    headers: {
        'accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.8',
        'Content-Type': 'multipart/form-data;',
    }
  })
   .then ...

I tried to convert here;

data.append( 'Image', this.state.image, this.state.image.name );
fetch( '/api/upload', data, {
    method: 'POST',
    headers: {
        'accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.8',
        'Content-Type': 'multipart/form-data;',
    },
    body: JSON.stringify(data)
  })
   .then ...

Returns 404 error, not found. What am I failing to do here?

Share Improve this question asked Jan 30, 2019 at 16:25 John107John107 2,2875 gold badges22 silver badges39 bronze badges 2
  • 2 I think you should remove the second argument data in your fetch function. Fetch only takes 2 arguments, the url and the options – Derek Nguyen Commented Jan 30, 2019 at 16:27
  • There are only two arguments to the fetch() function. Derek is correct. – Randy Casburn Commented Jan 30, 2019 at 16:29
Add a ment  | 

2 Answers 2

Reset to default 3

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', {
             method: 'GET',
             headers: {
               'Content-Type': 'application/json'
               },
             });
             const data = await response.json();
        // enter you logic when the fetch is successful
        //example: show success modal, clear form, route to another page etc.
             console.log(data);
           } catch(error) {
       // enter your logic for when there is an error,
       // example: open a modal with error message.
              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
            //example: show success modal, clear form, route to another page etc.
                 console.log(data);
               } catch(error) {
           // enter your logic for when there is an error,
           // example: open a modal with error message.
                  console.log(error)
                 } 
            }

asyncPostCall()

GET request using Promises:

  fetch('https://jsonplaceholder.typicode./posts', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
  },
})
  .then(res => res.json())
  .then(data => {
// enter you logic when the fetch is successful
//example: show success modal, clear form, route to another page etc.
    console.log(data)
  })
  .catch(error => {
// enter your logic for when there is an error,
// example: open a modal with error message.
   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
//example: show success modal, clear form, route to another page etc.
    console.log(data)
  })
  .catch(error => {
// enter your logic for when there is an error,
// example: open a modal with error message.
   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
        // example: show success modal, clear form, route to another page etc.
          console.log(`data: `, data)
       
        } catch (error) {
        // enter your logic for when there is an error,
         // example: open a modal with error message.
          console.log(`error: `, error)
        }
      }

axiosGetCall()

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."
      })
    // enter you logic when the fetch is successful
    // example: show success modal, clear form, route to another page etc.
      console.log(`data: `, data)
   
    } catch (error) {
    // enter your logic for when there is an error,
     // example: open a modal with error message.
      console.log(`error: `, error)
    }
  }


axiosPostCall()

fetch only takes two arguments.

fetch('/api/upload', {
  method: 'post',
  body:    JSON.stringify(data),
  headers: {
    'accept': 'application/json',
    'Accept-Language': 'en-US,en;q=0.8',
    'Content-Type': 'multipart/form-data;',
  },
})
.then(res => res.json())
.then(json => console.log(json));
发布评论

评论列表(0)

  1. 暂无评论