DEV Community

Tu Trinh
Tu Trinh

Posted on

Basic: Using Async and Await with Axios

Axios is a promise based HTTP client for the browser and Node.js. Axios makes it easy to send asynchronous HTTP request to REST endpoints and execute CRUD operations. It is used in Javascript or with a framework such as Vue.

Get

const getResponse = async () => {
     try {
          const response = await axios.get('url')
     } catch(err) {
          console.log('err')
     }
}
Enter fullscreen mode Exit fullscreen mode

Post

const createPost = async () => {
     const payload = {
          userid: 42,
          firstName: 'John',
          lastName: 'Doe'
     }

     try {
          // axios automatically serializes the payload to JSON.
          // no need to JSON.stringify({ userid: 42, ...})
          const res = await axios.post('url', payload)
     } catch(error) {
          console.log(error)
     }
}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (2)

Collapse
 
allan2012 profile image
Allan Kibet

Simple and great example

Collapse
 
khaled17 profile image
khaled-17

great example