Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue js 2 & Axios Post Request - Form

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
like image 647
Marketingexpert Avatar asked May 04 '17 12:05

Marketingexpert


People also ask

Is Vue 2 still used?

Everybody uses Vue 2 in 2021! You won't fall behind, you are not missing out, and your codebase is definitely not outdated. Keep your focus on developing amazing apps and when the Vue 3 ecosystem is ready for the migration we will all know it and we will have time in our turn to upgrade.

What is difference between Vue 2 and Vue 3?

In Vue 2, you implement only one single root node in the template but Vue 3 no longer requires a single root node for components that means it provides developer multiple root in the template.

Has Vue 3 been released?

The New Vue This soft launch process took longer than we hoped, but we are finally here: we are excited to announce that Vue 3 will become the new default version on Monday, February 7, 2022. Outside of Vue core, we have improved almost every aspect of the framework: Blazing fast, Vite-powered build toolchain.

Is Vue js better than React?

Both of them show excellent performance and now are used for building popular web apps. In fact, Vue is better for building complex web apps than React.


Video Answer


1 Answers

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/

like image 70
Egor Stambakio Avatar answered Oct 10 '22 08:10

Egor Stambakio