vue 的 axios 安装

安装

安装或者引入CDN文件

npm install axios
<script src="https://unpkg.com/axios/dist/axios.js"></script>
<!--<script src="https://unpkg.com/axios/dist/axios.min.js"></script>-->

GET

在Vue原型链上绑定,就可以全局使用$http方法

import axios from 'axios';
Vue.prototype.$http = axios;

然后我们就可以,其他地方使用的话,如同使用vue-resource一样,我们还可以在get或者post请求后面增加请求头header

this.$http.get("http://www.tuling123.com/openapi/api", {
    params: {
        key: "c75ba576f50ddaa5fd2a87615d144ecf",
        info: "先有鸡还是先有蛋"
    },
    header:{}
}).then((data) => {
    console.log(data);
    //success callback
}, (err) => {
    //error callback
})

POST

post请求比get请求复杂一点,首先降Content-Type格式为application/x-www-form-urlencoded,因为axiospost方法默认使用application/json格式编码数据,那么解决方案就有两种,一是后台改变接收参数的方法,另一种则是将axiospost方法的编码格式修改为application/x-www-form-urlencoded,这样就不需要后台做什么修改了

import axios from 'axios'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//全局更改
import qs from "qs";//配合qs模块转化post请求的参数,记得先npm install qs
Vue.prototype.$axios = axios;
Vue.prototype.$qs = qs;

然后在组件中这样使用

export default {
    this.$axios({
      method: "post",
      //headers: { "content-type": "application/x-www-form-urlencoded" },//局部更改
      url: "http://localhost:3000/users/test",
      data: this.$qs.stringify({
        name: ""
      })
    }).then(res => {
      console.log(res);
    });
  }
};

具体或者其他方法可以参考官方文档的这篇解决方案using-applicationx-www-form-urlencoded-format

代理

比如在vue-cli3中我们可以这样配置代理来解决跨域问题,在package.jsonbabel.config.js同级目录下新建vue.config.js文件写入以下代码

module.exports = {
    baseUrl: '/',
    devServer: {
        proxy: {
            '/api': {
                target: 'https://m.nubia.com',
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                  '^/api': ''
                }
            }
        }
    }
}

正常情况请求https://m.nubia.com/show/page/phoneType是会跨域的,经过上面配置,就可以用/api/show/page/phoneType代替来访问

this.$axios({
    method: "get",
    url: "/api/show/page/phoneType",
    //    /api/show/page/phoneType代替https://m.nubia.com/show/page/phoneType
}).then(res => {
    console.log(res);
});

原文:https://github.com/Wscats/vue-tutorial/issues/16

参考文档

 
原文地址:https://www.cnblogs.com/whx123/p/12094795.html