如何使用POST方法发送和访问参数

我正在使用Javascript为我的网页创建身份验证表单,并在客户端使用Vue JS,在服务器端使用NodeJS和Express JS。

在服务器端,我编写了post方法:

server.app.post("/login", function(req, res) {
    console.log(req.body.username);
})

在客户端上,我在html链接上的表单有一个Vue实例:

<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
  <div id="authent">
      <p>Username :</p>
      <input type="text" name="username" v-model="username" required>
      <p>Pwd :</p>
      <input type="password" name="password" v-model="password" required>
      <button v-on:click="authent">Login</button>
    </div>
    <script src='/authent/vue.js'></script>
    <script src='/authent/vue-resource.min.js'></script>
    <script src="authent.js"></script>
  </body>
</html>
window.onload = function () {
  var authent = new Vue({
    el: '#authent',
    data: {
      username: null,
      password: null
    },
    methods: {
      authent: function() {
        try {
          this.$http.post('/login', {"username": authent.username, "password": authent.password})
            .then(function(response) {
                console.log(response.body);
          })
        } catch (e) {
          console.log(e);
        }
      }
    }
  })
}

Apparently I wrongly send parameters in vue instance because on server side the req.body is undefined.

评论
  • kqui
    kqui 回复

    I'm not familiar with Vue, but can you try to use this.username instead of authent.username ?

    在您的devTools中,您可以看到已经看到了参数吗?确保这是一个前端问题。