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;

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>

方式二使用qs

第一步:安裝qs

npm install qs

第二步:在 main.js裏引入

import Axios from 'axios';
import Qs from 'qs';
Vue.prototype.$Qs = Qs;

在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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章