vue3.0代理配置以及接口封装

vue3.0代理配置以及接口封装
1.首先vue3.0是没有vue.config.js这个文件的,所以需要我们自己配置
在主目录下创建一个vue.config.js页面

//vue.config.js
const path = require("path");
const resolve = function(dir) {
  return path.join(__dirname, dir);
};
module.exports = {
  publicPath: process.env.NODE_ENV === "production" ? "./" : "./",
  outputDir: "dist",
  assetsDir: "static",
  lintOnSave: true, // 是否开启eslint保存检测
  productionSourceMap: false, // 是否在构建生产包时生成sourcdeMap
  chainWebpack: config => {
    config.resolve.alias
      .set("@", resolve("src"))
      .set("@v", resolve("src/views"))
      .set("@c", resolve("src/components"))
      .set("@u", resolve("src/utils"))
      .set("@s", resolve("src/service")); /* 别名配置 */
    config.optimization.runtimeChunk("single");
  },
  devServer: {
    /* 本地ip地址 */
    host: "localhost",
    port: "8080",
    hot: true,
    /* 自动打开浏览器 */
    open: false,
    overlay: {
      warning: false,
      error: true
    },
    /* 跨域代理 */
    proxy: {
        '/api': {
        target: 'xxx',//代理地址
        ws: true,
        changeOrigin: true,
        pathRewrite:{
            '^/api':''
        }
    }
}
  }
};

2.接口封装

//@/api/index.js
import request from '../utils/request';
let baseUrl = '/api';
// 添加文章接口
export const addArticle = query => {
    return request({
        url: baseUrl+'xxx',//接口地址
        method: 'get',
        params: query
    });
};

3.request.js

> import axios from 'axios';
> const service = axios.create({ timeout: 5000 }); 
>     config => {
>         return config;
>     },
>     error => {
>         console.log(error);
>         return Promise.reject();
>     } );
> 
> service.interceptors.response.use(
>     response => {
>         if (response.status === 200) {
>             return response.data;
>         } else {
>             Promise.reject();
>         }
>     },
>     error => {
>         console.log(error);
>         return Promise.reject();
>     } );
> 
> export default service;

4.接口调用

//页面引入
import { addArticle } from '@/api/index';
//调用
addArticle().then(res => {
        console.log(res);     
  });





你可能感兴趣的:(vue)