Vue js 2 & Axios Post Request - Form

Marketingexpert picture Marketingexpert · May 4, 2017 · Viewed 54k times · Source

I am trying to post my form using axios, but I am not able to get the data to my backend using expressjs

This is what I am doing:

<template>
 <form class="" method="post" @submit.prevent="postNow">
 <input type="text" name="" value="" v-model="name">
 <button type="submit" name="button">Submit</button>
 </form>
</template>

export default {
  name: 'formPost',
  data() {
    return {
      name: '',
      show: false,
    };
  },
  methods: {
   postNow() {
  axios.post('http://localhost:3030/api/new/post', {
    headers: {
      'Content-type': 'application/x-www-form-urlencoded',
    },
    body: this.name,
   });
  },
  components: {
    Headers,
    Footers,
  },
};

backend file:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/new/post', (req, res) => {
  res.json(console.log("this is working" + ' ' + req.body.name));
});

The error I am receiving is:

this is working undefined

Answer

Egor Stambakio picture Egor Stambakio · May 4, 2017

Axios post format:

axios.post(url[, data[, config]])

Your request should be:

axios.post('http://localhost:3030/api/new/post', 
    this.name, // the data to post
    { headers: {
      'Content-type': 'application/x-www-form-urlencoded',
      }
    }).then(response => ....);

Fiddle: https://jsfiddle.net/wostex/jsrr4v1k/3/