Vue3---Vue3项目集成axios(通过Promise封装并通过配置代理解决跨域)

  • 控制台安装axios
npm install axios --save
  • 创建文件:src/axios/index.js。通过Promise封装axios
import axios from 'axios';
axios.defaults.baseURL='/api'       //此路径为配置代理服务器时的代理路径

export default {
    get(url, data, responseType) { // url: 接口;路径;data: 请求参数;responseType:相应的数据类型,不传默认为json
        return new Promise((resolve, reject) => {
            axios({
                method: 'get',
                url,
                data,
                headers: {
                    Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8',
                    withCredentials: true,
                },
                //默认json格式,如果是下载文件,需要传 responseType:'blob'
                responseType: (responseType == null || responseType == '') ? 'json' : responseType
            }).then(response => {
                if (response.status == 200) {
                    //根据实际情况进行更改
                    resolve(response)
                } else {
                    reject(response)
                }
            })
        })
    },

    post(url, data, responseType) { // url: 接口;路径;data: 请求参数;responseType:相应的数据类型,不传默认为json
        return new Promise((resolve, reject) => {
            axios({
                method: 'post',
                url,
                data,
                headers: {
                    Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8',
                    withCredentials: true,
                },
                //默认json格式,如果是下载文件,需要传 responseType:'blob'
                responseType: (responseType == null || responseType == '') ? 'json' : responseType
            }).then(response => {
                if (response.status == 200) {
                    //根据实际情况进行更改
                    resolve(response)
                } else {
                    reject(response)
                }
            })
        })
    }
}
  • 创建配置文件:项目根目录/vue.config.js(和src同级)。配置代理解决跨域
module.exports = {      
    publicPath : '/',           //基本路径
    outputDir : 'dist',         //打包的包文件名
    assetsDir : 'static',       //css、js、img静态资源存放文件夹
    lintOnSave : false,         //是否在保存的时候使用 `eslint-loader` 进行检查。默认true
    runtimeCompiler : false,    //是否使用包含运行时编译器的 Vue 构建版本。默认false
    productionSourceMap : false,//生产环境不需要 source map,加速生产环境构建。默认true
   
    devServer: {                //webpack-dev-server配置
        host : 'localhost',       
        port : 8080,            //配置本项目运行端口
        proxy: {                //配置代理服务器来解决跨域问题
            '/api': {
                target: 'http://localhost:3000',      //配置要替换的后台接口地址
                changOrigin: true,                    //配置允许改变Origin
                pathRewrite: {
                    '^/api': ''
                }
            },
        }
    },
}
  • .main.js文件中导入封装好的axios,并进行全局挂载
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

const app = createApp(App)
app.use(store)
app.use(router)
app.mount('#app')

// 导入封装好的axios并挂载到Vue全局属性上
import Axios from './axios/index.js'
app.config.globalProperties.$axios = Axios
  • 组件中使用axios进行网络请求
<template>
  <div>
    <p></p>
  </div>
</template>
<script>
import { defineComponent, getCurrentInstance, onMounted } from 'vue'

export default defineComponent({
  name: '',
  setup(){
    const { ctx } = getCurrentInstance() // 获取上下文对象
    onMounted(() => {
      ctx.$axios.post('/playlist/hot', {}) // 网络请求
        .then(result => {
          console.log(result)
        }).catch(() => { /* */ })
    })

    return {}
  }
})
</script>

猜你喜欢

转载自blog.csdn.net/qq_39115469/article/details/113795713
今日推荐