Javascript Vue js 2 & Axios Post 请求 - 表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43783158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:09:36  来源:igfitidea点击:

Vue js 2 & Axios Post Request - Form

javascriptnode.jsexpressvue.jsaxios

提问by Marketingexpert

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

我正在尝试使用 axios 发布我的表单,但我无法使用 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

回答by Egor Stambakio

Axios postformat:

Axiospost格式:

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

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/

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