Vue js 2& Axios Post Request - 表格

时间:2017-05-04 12:39:06

标签: 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,
  },
};

后端文件:

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));
});

我收到的错误是:

this is working undefined

1 个答案:

答案 0 :(得分:27)

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 => ....);

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