Skip to content
New issue

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 搭建的项目处理不同环境下请求不同域名的问题 #31

Open
chenyinkai opened this issue Mar 15, 2018 · 5 comments
Labels

Comments

@chenyinkai
Copy link
Owner

chenyinkai commented Mar 15, 2018

vue-cli 搭建的项目处理不同环境下请求不同域名的问题

使用 vue-cli 开发项目过程中, 根据开发环境和正式环境不同, 我们往往需要请求不同域名下的后台接口, 这时候, 该怎么去设置, 达到同一种写法可以根据环境不同而自动切换请求域名呢? 本文将会介绍两种配置方式.

本文中所有请求都是使用 axios

  1. 修改 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"' // 开发环境接口地址(这里是增加的内容)
})
  1. 修改 config/prod.env.js (正式环境的配置)
'use strict'
module.exports = {
  NODE_ENV: '"production"',
  API_HOST: '"http://localhost:3000"'  // 正式环境接口地址(这里是增加的内容)
}
  1. 使用 axios 发送请求
axios.get(process.env.API_HOST + '/api/userData') // 请求前加上 `process.env.API_HOST`
  .then(data => {
    console.log(data)
  })

第二种方法主要使用 axios 的创建实例的用法

main.js 配置 axios

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)
  })
@chenyinkai chenyinkai added the vue label Mar 15, 2018
@chenyinkai chenyinkai changed the title vue-cli 搭建的项目处理不同环境请求不同域名的问题 vue-cli 搭建的项目处理不同环境下请求不同域名的问题 Mar 15, 2018
@zqdeveloper
Copy link

第一种方法我找不到且打印不出来API_HOST 打印出来的对象中没有这个属性

@zqdeveloper
Copy link

image
image

@chenyinkai
Copy link
Owner Author

@1052105484 ~~

@cat-eat-fish
Copy link

我想 问 有用吗

@chenyinkai
Copy link
Owner Author

@cat-eat-fish https://github.com/chenyinkai/cykspace/blob/master/src/api/index.js 这是我项目中的使用方法。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants