Vue将数据传递给POST方法

时间:2017-02-19 12:10:21

标签: javascript vue.js

将数据传递给Vuejs String selectQuery = "SELECT * FROM " + InteractionSchema.TABLE + " interaction " + " WHERE interaction." + InteractionSchema.KEY_owner + " =? ORDER BY datetime(" + InteractionSchema.KEY_date + ") DESC LIMIT 15"; 方法时遇到问题。我使用的是vue-resource,在文档中是:

post

我想放置标题,它可以正常工作(服务器读取标题正确):

this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

但如果我尝试添加任何数据出错,例如我尝试过:

 this.$http.post(
      'http://localhost:8081/login', 
      {
        headers: {
          'Accept': 'application/json'
        }
      });

或定义一些数据并放在那里:

this.$http.post(
      'http://localhost:8081/login',
       {username: 'admin'},
      {
        headers: {
          'Accept': 'application/json'
        }
      });

并且对于两个解决方案,body部分始终为空 - 使用以下命令检查来自请求的正文数据:

this.$http.post(
      'http://localhost:8081/login', 
       this.data,
      {
        headers: {
          'Accept': 'application/json'
        }
      });

可能问题出现在vue.js代码中,因为它可以正常工作,我发送邮递员的任何请求。我该怎么办?

2 个答案:

答案 0 :(得分:3)

您是否尝试过发送帖子请求而不包含带帖子的第三个参数

this.$http.post('url', {something: "string"})
  .then ((res)=> console.log (res.body))
  .catch ((error)=> console.log(error))

这对我有用......

另一件事,你确定你在后端正确获取请求数据......它看起来像python,我不完全确定它是如何工作的。

答案 1 :(得分:0)

如果要发送多个JSON值,这里是一个示例。

const vm = new Vue({
  el: '#app',
  data: {
    email: '',
    password: ''
  },
  methods: {
    getPosts() {
      return axios.post('http://127.0.0.1:5000/login',
        { email: this.email,
          password: this.password
        },
        { headers: {
        'Content-type': 'application/json',
        }
      }).then((response) => {
        console.log('email: ' + this.email);
        console.log('password: ' + this.password);
      }).catch( error => { 
        console.log('error: ' + error); 
      });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="email" name="email" v-model="email">
  <input type="password" name="password" v-model="password">
  <button v-on:click="getPosts()">Login</button>
</div>