Vue将数据传递给POST方法

问题描述 投票:3回答:2

我有一个问题,将数据传递给Vuejs post方法。我正在使用vue-resource,在文档中是:

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

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

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

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

 body = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

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

javascript vue.js
2个回答
3
投票

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

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

这对我有用......

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


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>
© www.soinside.com 2019 - 2024. All rights reserved.