当前位置:   article > 正文

axios post方式传递参数_axios post 参数

axios post 参数

方式一:使用URLSearchParams

第一步:在main.js里 设置配置,修改Content-Type

import Axios from 'axios';
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$Axios = Axios;
  • 1
  • 2
  • 3

jquery在执行post请求时,会设置Content-Type为application/x-www-form-urlencoded,所以服务器能够正确解析,而使用原生ajax、axios请求时,如果不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。

第二步:在组件vue里

<script>
  export default {
    methods: {
      getData(id) {
        let url = "http://localhost:8080/VueServer/news?op=detail";
        let params = new URLSearchParams();
        params.append("id",id.nid);
        this.$Axios({
          method: 'post',
          url: url,
          data: params  //params会添加到url的请求字符串中,用于get请求。而data是添加到请求体(body)中的, 用于post请求。
        }).then(res => {
          this.msg = res.data;
          console.info(res);
        }).catch(error => {
          console.info(error);
        });
      }
    },
    mounted() {
      //获取动态传值
      console.info(this.$route.params);
      this.getData(this.$route.params);
    }
  }
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

方式二使用qs

第一步:安装qs

npm install qs

第二步:在 main.js里引入

import Axios from 'axios';
import Qs from 'qs';
Vue.prototype.$Qs = Qs;
  • 1
  • 2
  • 3

在vue组件里面请求方法

<script>
  export default {
    methods: {
      getData(id) {
        let url = "http://localhost:8080/VueServer/news?op=detail";
        let params = this.$Qs.stringify({
          id: id.nid
        })
        this.$Axios({
          method: 'post',
          url: url,
          data: params
        }).then(res => {
          this.msg = res.data;
          console.info(res);
          console.info(this.msg);
        }).catch(error => {
          console.info(error);
        });
      }
    },
    mounted() {
      //获取动态传值
      console.info(this.$route.params);
      this.getData(this.$route.params);
    }
  }
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/279864
推荐阅读
相关标签
  

闽ICP备14008679号