Vue js 2&Axios Post Request - Form

Mar*_*ert 19 javascript node.js express vue.js axios

我正在尝试使用axios发布我的表单,但我无法使用expressjs将数据提供给我的后端

这就是我在做的事情:

<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,
  },
};
Run Code Online (Sandbox Code Playgroud)

后端文件:

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));
});
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

this is working undefined
Run Code Online (Sandbox Code Playgroud)

Ego*_*kio 33

Axios post格式:

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

您的要求应该是:

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

小提琴:https://jsfiddle.net/wostex/jsrr4v1k/3/

  • @Pradiptadas 你可以发布 `{ name: this.name }` 而不是 `this.name` 。 (2认同)