简体   繁体   中英

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

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/

 <template> <div id="content"> <h1>...</h1> <div> <label>Product Name</label> : <input type="text" id="txt1" v-model="model.productName" /> </div> <div> <label>Desciription</label> : <input type="text" id="txt2" v-model="model.descrption" /> </div> <div> <button type="button" v-on:click="saveClick">Save</button> </div> </div> <hr /> <hr /> <h1>...</h1> <table border="1" style="margin:auto"> <thead> <tr> <th style="width: 100px">ID</th> <th style="width: 100px">Product Name</th> <th style="width: 100px">Desciription</th> <th style="width: 100px"></th> </tr> </thead> <tbody> <tr v-for="item in model.list" v-bind:key="item.id"> <td>{{ item.id }}</td> <td>{{ item.productName }}</td> <td>{{ item.descrption }}</td> <td><button type="button" v-on:click="deleteClick(item.id)">Delete</button></td> </tr> </tbody> </table> </template> <script> import axios from "axios"; export default { name: "Product", data: function () { return { model: { productName: "", descrption: "", }, list: [], }; }, methods: { saveClick() { axios .post("http://example.com", this.model) .then((resp) => { this.getList(); alert("success" + resp.data.id); }); }, getList() { axios.get("http://example.com").then((resp) => { this.model.list = resp.data; }); }, deleteClick(id) { axios.delete("http://example.com" + id).then(() => { this.getList(); alert("success"); }); } }, mounted: function () { this.getList(); }, }; </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM