Vue axios

前提条件:vue-cli项目
安装:

npm install axios --save-dev;
//还需要序列化字符串
npm install qs;
//以上是axios发送带参请求需要的必须组件,直接复制到cmd或者控制器按回车即可!

在main.js中导入:

//引入axios
import axios from "axios";
// 引入序列化字符串文件
import QS from "qs";
//加入到原型链中
Vue.prototype.$axios = axios;
Vue.prototype.$qs = QS;
//将http挂在Vue的原型对象上面方便使用
axios.defaults.timeout = 5000; //响应时间
axios.defaults.headers.post["Content-Type"] ="application/x-www-form-urlencoded;charset=UTF-8"; //配置请求头
axios.defaults.beseURL = ""; //配置请求的地址

复制以下代码,在一个简洁的Vue项目中粘贴过去即可,修改请求地址就可以使用

//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
    //在发送请求之前做某件事
    if(config.method  === 'post'){
        config.data = qs.stringify(config.data);
    }
    return config;
},(error) =>{
    console.log('错误的传参')
    return Promise.reject(error);
});

//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) =>{
    //对响应数据做些事
    if(!res.data.success){
        return Promise.resolve(res);
    }
    return res;
}, (error) => {
    console.log('网络异常')
    return Promise.reject(error);
});

//返回一个Promise(发送post请求)
export function fetchPost(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}
返回一个Promise(发送get请求)
export function fetchGet(url, param) {
    return new Promise((resolve, reject) => {
        axios.get(url, {params: param})
           .then(response => {
              resolve(response)
           }, err => {
              reject(err)
           })
           .catch((error) => {
             reject(error)
       })
   })
}
export default {
    fetchPost,
    fetchGet,
}

开发环境一般要跨域,解决跨域问题(设置代理):vue-cli 3.0的在 package.json 同级目录新建一个 vue.config.js 文件,加入下面代码,其他版本找到配置文件的devServer加入代码

module.exports = {
    //axios域代理,解决axios跨域问题
    baseUrl: '/',
    devServer: {
        proxy: {
            '': {
                target: 'http://192.168.0.108:8090',
                changeOrigin: true,
                ws: true,
                pathRewrite: {

                }
            }
        }
    }
}

修改完后记得重启项目应用配置
然后就到收获的时候了,在要请求的vue模块中导入并使用:

import https from '../https.js'   // 注意用自己的路径

// 请求后台数据==================
      loginPost: function () {
      let params ={'username': 'admin', 'password': 'admin123', 'rememberMe': 'true','isMobile':'1'}
       https.fetchPost('/login',params ).then((data) => {
           this.base.token = data.data.token    
 // console.log("this.base.tokenthis.base.token",this.base.token)
           this.indexPost2(this.rres)
           }).catch(err=>{
           console.log(err)
          })
    },
      indexPost2:function (date) {
       var this_ = this
       this_.check = false
       var jobj ={data:{'menuDate': date,'token':this.base.token}}
       let string  = JSON.stringify(jobj)
       let params = {dailyInfo:string}
https.fetchPost('/meals/mobile/getDailyMenuByDate', params)
       .then((data) => {
       this_.base.indexData = data
       this_.check = true
// console.log('thenthenthenthen',data)
    })
       .catch((err)=>{
       console.log(err)
      })
          },
// ================================================
},

发送带参的post请求(简化版)

//序列化字符串
   let data = this.$qs.stringify({ metterIds: "1,2,3" });
      this.$axios
        .post("http://localhost:3000/users", data, {
          headers: { "Content-Type": "application/x-www-form-urlencoded" }
        })
        .then(res => {
          console.log(res);
        });
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐