美文网首页
Vite中配置vue环境变量并请求

Vite中配置vue环境变量并请求

作者: 秋玄语道 | 来源:发表于2022-04-15 12:17 被阅读0次

1、在目录下新建如下几个变量

  • .env.development(开发环境)
# just a flag
ENV = 'development'

# .env.development
# base api
VITE_APP_BASE_URL = '/dev-api'
  • .env.production(生产环境)
# just a flag
ENV = 'production'

# .env.production
# base api
VITE_APP_BASE_URL= '/prod-api'

2、vite.config.js配置

export default defineConfig({
  server: {
    // 服务配置
    port: port, // 类型: number 指定服务器端口;
    open: true, // 类型: boolean | string在服务器启动时自动在浏览器中打开应用程序;
    cors: true, // 类型: boolean | CorsOptions 为开发服务器配置 CORS。默认启用并允许任何源
    proxy: {
      '/dev-api': {
        target: 'http://8.135.1.141',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/dev-api/, '')
      },
       '/prod-api': {
          target: 'http://8.135.1.141',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/prod-api/, '')
        }
      }
    },
 })

3、store配置

import { loginReq } from '@/api/user'
const actions = {
  // user login
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  login({ commit }, data) {
    return new Promise((resolve, reject) => {
      loginReq(data)
        .then((res) => {
          if (res.code === 20000) {
            console.log(res.data)
            //commit('SET_Token', res.data?.jwtToken)
            setToken(res.data?.jwtToken)
            resolve()
          } else {
            reject(res)
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

4、axios请求

import request from '@/utils/request'
export function loginReq(data) {
  return request({
    url: '/micro-service-api/integration-front/user/loginValid',
    data,
    method: 'post',
    bfLoading: false,
    isParams: true,
    isAlertErrorMsg: false
  })
}

5、页面请求

let loginReq = () => {
  loading.value = true
  store
    .dispatch('user/login', param)
    .then(() => {
      ElMessage({ message: '登录成功', type: 'success' })
      loading.value = false
      router.push("/");
    })
    .catch((res) => {
      loading.value = false
    })
}

相关文章

网友评论

      本文标题:Vite中配置vue环境变量并请求

      本文链接:https://www.haomeiwen.com/subject/xdnfertx.html