在vue中使用axios发送请求的方式

919 阅读1分钟

第一步:

先安装axios,使用:npm i axios -S

第二步:修改main.js文件

import axios from 'axios'
//其中qs模块已经默认封装进axios模块里了,所以这里不需要安装直接引用即可

import qs from 'qs'//(作用是为了的序列化post的参数)

//这里是针对post请求修改请求头(因为axios的默认格式为Request Payload,这就导致浏览器无法正常请求,而jquery的ajax方法内部实际做了修改)

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
charset=UTF-8';

//这里是将axios绑定到vue上,以后组件页面就不需要引入了,可直接使用this.$http.方法即可。

Vue.prototype.$http = axios

第三步:组件页面的使用

  • GET请求

      //方式一:
      this.$http({
          method:'get',
          url:'http:192.168.168.1:8080/Common/news/articles/v1.0/RdxwList?AAB301=420000',
      }).then(function (res) {
          console.log(res);
      }).catch(function(err){
          console.log(err);
      })
      //方式二:
      this.$http.get('http:192.168.168.1:8080/Common/news/articles/v1.0/RdxwList?AAB301=420000').then(function(res){
          console.log(res);
      }).catch(function(err){
          console.log(err);
      })
    
  • POST请求

注意:post请求的参数必须使用此种方式进行转换,否则也无法发送成功,当然还有另一种方式, 需要使用qs进行参数序列化(建议使用)。

//方式一:
var params = new URLSearchParams();//这里作用类似qs,目的是为了序列化参数。但有兼容问题
params.append('UCE197','021be8277c0545d0b07059eb2e27230e')
params.append('UCB001','4cb5126b89de4712b7f989c37129aa14')
params.append('PAGE','1')
params.append('LINAGE','5')

this.$http({
    method:'post',
    url:'http:192.168.168.1:8080/manage/business/JobIntroduction/resume/v1.0/recommend',
    data:params
}).then(function(res){
    console.log(res);
}).catch(function(err){
    console.log(err);
})

//方式二:
this.$http.post('http:192.168.168.1:8080/manage/business/JobIntroduction/resume/v1.0/recommend',params).then(function(res){
    console.log(res);
}).catch(function(err){
    console.log(err);
})
  • 2、使用qs进行参数序列化(qs默认装在了axios中,使用时直接Vue.use即可,不需要再安装qs)

      //方式一:
      var params = {
          UCE197:'021be8277c0545d0b07059eb2e27230e',
          UCB001:'4cb5126b89de4712b7f989c37129aa14',
          PAGE:1,
          LINAGE:5
      };
    
      this.$http({
          method:'post',
          url:'http:192.168.168.1:8080/manage/business/JobIntroduction/resume/v1.0/recommend',
          data:qs.stringify(params)
      }).then(function(res){
          console.log(res);
      }).catch(function(err){
          console.log(err);
      })
      
      //方式二:
      var params = {
          UCE197:'021be8277c0545d0b07059eb2e27230e',
          UCB001:'4cb5126b89de4712b7f989c37129aa14',
          PAGE:1,
          LINAGE:5
      };
      
      this.$http.post('http:192.168.168.1:8080/manage/business/JobIntroduction/resume/v1.0/recommend',qs.stringify(params)).then(function(res){
          console.log(res);
      }).catch(function(err){
          console.log(err);
      })