您当前的位置: 首页 >  ios

axios post方式传递参数

梁云亮 发布时间:2020-05-12 13:19:49 ,浏览量:2

方式一:使用URLSearchParams 第一步:在main.js里 设置配置,修改Content-Type
import Axios from 'axios';
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$Axios = Axios;

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

第二步:在组件vue里

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

方式二使用qs 第一步:安装qs

npm install qs

第二步:在 main.js里引入
import Axios from 'axios';
import Qs from 'qs';
Vue.prototype.$Qs = Qs;
在vue组件里面请求方法

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

关注
打赏
1688896170
查看更多评论

梁云亮

暂无认证

  • 2浏览

    0关注

    1121博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0558s