Vue使用Axios实现http请求以及解决跨域问题

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。Axios的中文文档以及github地址如下:

中文:https://www.kancloud.cn/yunye/axios/234845

github:https://github.com/axios/axios

vue路由文档:https://router.vuejs.org/zh/

一、安装Axios插件

npm install axios --save

二、在main.js中引入Axios库

import Axios from "axios"
//将axios挂载到原型上
Vue.prototype.$axios = Axios;

//配置全局的axios默认值(可选)

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

三、使用get方式的http请求

this.$axios.get("请求url",{param:{}})
           .then(function(response){
                  console.info(response.data);
                 })
           .catch(function(error){
                   console.info(error);
                 });

四、使用post方式的http请求

this.$axios.post("请求路径",{})
           .then(function(response){
                  console.info(response.data);
                 })
           .catch(function(error){
                  console.info(error);
                 });

注意使用上述post方式提交参数的时候存在问题,axios中post的请求参数格式是form-data格式。而上述json串的格式为x-www-form-urlencoded格式

例如:

form-data:?name="zhangsan"&age=10 

x-www-form-urlencoded:{name:"zhangsan",age:10}

此时我们需要将数据格式作转换,在当前页面引入第三方库qs

import qs from "qs"

此时上述参数改为:

this.$axios.post("请求路径",qs.stringify({}))
           .then(function(response){
                  console.info(response.data);
                 })
           .catch(function(error){
                  console.info(error);
                 });

五、Axios的拦截器

  拦截器在main.js中进行配置,配置如下:

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

基于以上的拦截器,我们可以对请求的数据或者是响应的数据做些处理,就拿上面post方式的请求参数格式举个例子,通过拦截器我们可以对所有的post方式的请求参数在发出请求之前作出转换:

import qs from "qs"


// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 参数格式转换
    if(config.method=="post"){
        config.data = qs.stringify(config.data);
    }
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

  因此基于拦截器我们在post请求的时候可以直接使用from-data的格式,不需要每次都编码转换

 六、前端跨域解决方案(了解)

描述:由于使用vue脚手架的目的就是使前后端分离,前端请求后端的数据在测试阶段设计到跨域请求问题,在前端中我们可以通过如下配置解决跨域请求问题。

  第一步(在config文件夹下的index.js中进行如下修改)

proxyTable:{
     "/api":{
         target:"后端提供服务的前缀地址",
         changeOrigin:true,
         pathRewrite:{
              '^/api':''
         }
     }
},

  第二步(在main.js中添加一个代理)

Vue.prototype.HOST='/api'

 再进行请求的时候只需要使用url = this.HOST+"请求的Mappering地址"即可

(注意:在上述过程中修改了config下的配置文件,服务需要重新启动,才能生效)

  声明:此种跨域只适用于测试开发阶段,项目正式上线并不实用,需要后端去处理跨域问题

猜你喜欢

转载自blog.csdn.net/LJJ1338/article/details/81812035