【问题标题】:How to convert axios to fetch?如何将axios转换为fetch?
【发布时间】:2019-06-24 00:00:18
【问题描述】:

我熟悉使用 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 错误,未找到。 我在这里没有做什么?

【问题讨论】:

  • 我认为您应该删除 fetch 函数中的第二个参数data。 Fetch 只需要 2 个参数,url 和选项
  • fetch() 函数只有两个参数。德里克是正确的。

标签: javascript node.js axios fetch-api


【解决方案1】:

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

【讨论】:

    【解决方案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', {
                 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()
    

    使用 Promises 获取请求:

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

    使用 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
    //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 获取请求:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 2022-01-15
      • 2016-09-02
      • 2021-05-22
      • 2021-12-29
      相关资源
      最近更新 更多