We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
使用 vue-cli 开发项目过程中, 根据开发环境和正式环境不同, 我们往往需要请求不同域名下的后台接口, 这时候, 该怎么去设置, 达到同一种写法可以根据环境不同而自动切换请求域名呢? 本文将会介绍两种配置方式.
vue-cli
本文中所有请求都是使用 axios
修改 config/dev.env.js (开发环境的配置)
config/dev.env.js
'use strict' const merge = require('webpack-merge') const prodEnv = require('./prod.env') module.exports = merge(prodEnv, { NODE_ENV: '"development"', API_HOST: '"http://localhost:3000"' // 开发环境接口地址(这里是增加的内容) })
修改 config/prod.env.js (正式环境的配置)
config/prod.env.js
'use strict' module.exports = { NODE_ENV: '"production"', API_HOST: '"http://localhost:3000"' // 正式环境接口地址(这里是增加的内容) }
使用 axios 发送请求
axios
axios.get(process.env.API_HOST + '/api/userData') // 请求前加上 `process.env.API_HOST` .then(data => { console.log(data) })
第二种方法主要使用 axios 的创建实例的用法
在 main.js 配置 axios
main.js
import axios from 'axios' const host = process.env.NODE_ENV === 'development' ? 'dev api host' : 'prod api host' // 根据 process.env.NODE_ENV 的值判断当前是什么环境 const instance = axios.create({ baseURL: host }) Vue.prototype.$http = instance
在组件中调用
this.$http.get('/api/userData') .then(data => { console.log(data) })
The text was updated successfully, but these errors were encountered:
第一种方法我找不到且打印不出来API_HOST 打印出来的对象中没有这个属性
Sorry, something went wrong.
@1052105484 ~~
我想 问 有用吗
@cat-eat-fish https://github.com/chenyinkai/cykspace/blob/master/src/api/index.js 这是我项目中的使用方法。
No branches or pull requests
vue-cli 搭建的项目处理不同环境下请求不同域名的问题
一
二
The text was updated successfully, but these errors were encountered: