如何将axios转换为fetch?

时间:2019-01-30 16:25:04

标签: javascript node.js axios fetch-api

我熟悉使用Axios发布数据,但是尝试使用fetch代替。我该如何转换为提取请求,我认为我所做的是正确的...

const data = new FormData();

以下axios请求有效:

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 ...

我试图在这里转换;

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 ...

返回404错误,未找到。 我在这里不能做什么?

2 个答案:

答案 0 :(得分:0)

fetch仅接受两个参数。

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));

答案 1 :(得分:0)

2021 答案:以防万一您登陆这里寻找与 axios 相比如何使用 async/await 或 promise 发出 GET 和 POST Fetch api 请求。

我使用 jsonplaceholder fake API 来演示:

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

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

使用 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
            //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()

使用 Promise 的 GET 请求:

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

使用 Promise 的 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
//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)
  })  

使用 Axios 的 GET 请求:

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

使用 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."
      })
    // 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()