vue之axios请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30299243/article/details/82148475

1,利用npm安装npm install axios --save

2,配置

(1)main.js里:

import Axios from 'axios'

// 配置请求信息
var $http = Axios.create({
  baseURL: '请求路径',
  timeout: '3000',  //请求超时时间
  headers: {'X-Custom-Header': 'foobar'}     //header传值,例如:Authorization
})

Vue.prototype.$http = $http

(2)config里面的index.js:

assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
  '/api': {

    target: '域名',   //后台给的域名

    changeOrigin: true,
    pathRewrite: {
      '^/api':'/api'
    }
  }

},

3,使用;登录的点击事件

import axios from 'axios';

methods: {
  login() {  
    if (this.username == "" || this.password == "") {
       alert("请输入用户名或密码")

    } else {

      var data = new URLSearchParams();   //一定要这样写,否则后台收不到参数的

      data.append('name', this.username);       //你要传给后台的参数值 key/value

      data.append('password', md5((this.username+this.password)));

      //password 这里用了MD5加密的,可根据自己的情况而定

      axios.post('/api/backManage/userLogin', data).then(function (res) {  //后台给的接口名
        console.log(res);

        if(res.data.error==0){

          //后台返回的错误码,如果是0表示请求正确,继续操作,否则给客户一个提示框

        }else {
          alert(res.data.msg);
        }

      }).catch(function (error) {

      });
    }
  },
}

猜你喜欢

转载自blog.csdn.net/qq_30299243/article/details/82148475