思路:分别封装get和post请求

文件结构如下
——src
	——api
		——api.js       封装项目接口
		——request.js   封装axios请求
——assets               用来存放项目的所有静态资源
——compoents            用来存放封装的公共的组件
——views                用来存放一般的组件
——vue.config.js        跨域配置

vue.config.js文件

module.exports = {
    publicPath: '', // 项目部署目录
    outputDir: 'build', //项目编译后的存放目录
    assetsDir: 'static', //项目编译后的静态资源存放目录
    indexPath: 'index.html', //项目编译后的index.html文件存放位置
    devServer: {
	        proxy: {
	            '/api': {  //  /api标识拦截以/api开头的请求路径,将target路径放到请求之前
	                target: https://www.vue-js.com',  //跨域的域名,不需要写路径
	                ws: true, //支持websocket
	                changeOrigin: true, //开启跨域调用
	            },
	            '/api': {
	                 target: 'https://www.vue-js.com/api', //域名后带有了路径,拼接请求路径时,会多出一个/api
	                 ws: true, //支持websocket
	                 changeOrigin: true, //开启跨域调用
	                 pathRewrite:{//将/api重写成空字符
	                     '^/api': ''
	                 }
	            }
        }
    }
}

在页面中请求

<template>
  <div>
    <button @click="send">测试</button>
  </div>
 
</template>

<script>
import axios from 'axios';           //直接使用axios.get请求
import {test} from "../request/api"; //api.js中引入封装好的axios函数
export default {
  methods:{
  	//send函数中使用了两种发送请求的写法,依次为axios.get方法和封装的axios.get()
    send(){
		//这里使用的请求路径是vue官方文档的测试接口
		//如果vue.config.js文件中proxy属性的target值带有路径,拼接路径时就会出现两个/api,这是需要开启路径重写pathRewrite,将target值中的路径重写为空字符
		//axios.get("https://www.vue-js.com/api/api/v1/topics") =>axios.get("https://www.vue-js.com/api/v1/topics")
      axios.get("/api/v1/topics").then(res=>{
        console.log(res);
      })
		

	//使用封装好的axio,请求路径在api.js文件中
      test().then(res=>{
      	console.log(res)
      });
    }
  }
};
</script>

<style scoped>

</style>

api.js文件

//发请求给服务端

//引入request.js中暴露的sendGet,sendPost函数
import {sendGet,sendPost} from './request.js';

export let test = () =>sendGet('/api/v1/topics');

request.js文件

import axios from "axios";
import qs from 'qs';
import router from 'vue-router';
import Vue from 'vue';

//if(process.env.NODE_ENV == 'development'){//开发环境
    //Vue.prototype.$imgHost = 'http://localhost:3000';
//}

//if(process.env.NODE_ENV == 'production'){//生产环境
   // Vue.prototype.$imgHost = '';
//}


//请求拦截器
axios.interceptors.request.use(config =>{
	// console.log(config,'请求拦截器参数');
	
    console.log('本次请求地址为:',config.url);
    
    //将token值从本地储存或sessionStorage中取出
     let curToken = localStorage['userinfo'] ? JSON.parse(localStorage['userinfo']) : '';
	
    //let curToken = sessionStorage.getItem('userinfo') ? JSON.parse(sessionStorage.getItem('userinfo')) : '';

    
	//发送请求之前设置请求头值为token
    if(curToken){
        config.headers.authorization = curToken;
    }
 
    //放行请求
    return config;
})

//响应拦截器
axios.interceptors.response.use(config=>{
    // console.log(config,'响应拦截器参数');
    
    //判断参数中状态码是否正确
    if(config.data.code != 200){
        // alert(config.data.msg);
    }
    if(config.data.code == 403){
        $router.push('/login')
    }
    //放行响应
    return config;
})

//发送axios的get请求
export function sendGet(url,params={},headers={}){
    // axios.get('/api/getbanner',{params:{},headers:{}});
    return axios.get(url,{params,headers});
}


//发送axios的post请求 
//data整体是一个对象,header是对象嵌套格式为,{headers:{}}

//如果有文件上传,传参时就将isFile改为true
export function sendPost(url,params={},isFile = false,headers={}){
    let datas = '';
    let forms = new FormData();
    // console.log(forms,9998);
    if(isFile){//params参数中含有文件上传
        for(let key in params){
            forms.append(key,params[key]);
        }
        datas = forms;
    }else{//params参数中不含文件上传
        //将params参数对象格式转换为键值对格式
        datas = qs.stringify(params); 
    }

    return axios.post(url,datas,{headers});
}
Logo

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

更多推荐