How to make a POST request in Vue.js

in Code Write a comment

Learn how to make POST requests in Vue.js. In front-end development, you’ll often make POST requests when submitting a form.

I’ve already described how to make a GET request in Vue.js.

We’ll be using axios, a promise based HTTP client for the browser and node.js, to make this API request.

Making a POST request in Vue.js

axios.post('/user', {
    firstName: 'Renat',
    lastName: 'Galyamov'
  })
  .then(function (response) {
    console.log(response)
  })
  .catch(function (error) {
    console.log(error)
  })

You should replace '/user' with your own URL.

Alternatively, you can perform a POST request in axios by passing config to your request.

// Send a POST request
axios({
  method: 'post',
  url: '/user/1',
  data: {
    firstName: 'Renat',
    lastName: 'Galyamov'
  }
})

A real-life example of POST request in Vuex

SAVE_USER ({ commit, state }, { user }) {
  return new Promise((resolve, reject) => {
    axios.post(process.env.VUE_APP_BASE_URL + 'api/users/', user, config).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

Hi, I'm Renat 👋

 


In the example above, we’re using JavaScript Promises for the eventual completion of the request.

To save your development time, you can move your app’s base URL to a separate config file. And make it change automatically for development and production sites.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-post-request

PS: Make sure you check other Vue.js tutorials.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment