DEV Community

Tu Trinh
Tu Trinh

Posted on

4 1

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

Top comments (2)

Collapse
 
khaled17 profile image
khaled-17

great example

Collapse
 
allan2012 profile image
Allan Kibet

Simple and great example

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay