如何将获取转换为axios

时间:2019-01-14 21:27:22

标签: node.js reactjs

我有以下一段完美的代码。但是,我的任务是用axios代替fetch。您能否指导一下,axios中正确的代码替换是什么?

const create = async (credentials, software) => {
  return await fetch('/api/software/create', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + credentials.t
    },
    credentials: 'include',
    body: JSON.stringify(software)
  })
    .then((response) => {
      return response.json()
    }).catch((err) => console.log(err))
}

create({ t: jwt.token }, data)
    .then((data) => {
      if (data.error) {
        this.setState({ error: data.error })
      } else {
        this.props.dispatch(initSoftware()); //if successful get the list of softwares in redux store
      }
    })

数据变量是一个对象,它保持req.body等价物... 上面的代码是用react编写的,在onSubmit事件处理程序中调用了create()。

我确定如果我使用axios,create()将被消除..但是如何?请指导。

2 个答案:

答案 0 :(得分:1)

它应该与您现在拥有的没什么不同,但是类似这样的东西...

const create = async (credentials, software) => {
  return await axios({
    url: '/api/software/create'
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + credentials.t
    },
    withCredentials: true,
    data: JSON.stringify(software)
  })
    .then((response) => {
      return response.data;
    }).catch((err) => console.log(err))
}

create({ t: jwt.token }, data)
    .then((data) => {
      if (data.error) {
        this.setState({ error: data.error })
      } else {
        this.props.dispatch(initSoftware()); //if successful get the list of softwares in redux store
      }
    })

请注意,您要查找的数据应位于名为data的属性中。

有关更多信息,请查阅API参考here

答案 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');
                 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()

使用 Promise 的 GET 请求:

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

使用 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
    console.log(data)
  })
  .catch(error => {
  // enter your logic for when there is an error (ex. error toast)
   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
              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."
      })
   // 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()