300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > vue2.0配置代理 api 开发环境 生产环境

vue2.0配置代理 api 开发环境 生产环境

时间:2019-09-10 20:57:38

相关推荐

vue2.0配置代理 api 开发环境 生产环境

业务场景:只需内网调用接口,不需要ngix,所以生产环境没有跨域问题不用api代理,但是本地环境有跨域问题要做代理。

实现需求:本地环境有api,生产环境没有api

以下是实现方法:

1、 config/index.js

'use strict'const path = require('path')module.exports = {dev: {// PathsassetsSubDirectory: 'static',assetsPublicPath: '/',proxyTable: {'/api/**': {//设置你调用的接口域名和端口号 别忘了加httptarget: 'http://192.168.1.159:60080',// target: 'http://192.168.1.162:60080',changeOrigin: true,pathRewrite: {'^/api': '' //这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可}},'/api2/**': {target: 'http://139.159.185.67:9208', //changeOrigin: true,pathRewrite: {'^/api2': '' //这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可}}},// Various Dev Server settingshost: '0.0.0.0', // can be overwritten by process.env.HOSTport: 8081, // can be overwritten by process.env.PORT, if port is in use, a free one will be determinedautoOpenBrowser: false,errorOverlay: true,notifyOnErrors: true,poll: false, // /configuration/dev-server/#devserver-watchoptions-/*** Source Maps*/devtool: 'cheap-module-eval-source-map',cacheBusting: true,cssSourceMap: true},build: {// Template for index.htmlindex: path.resolve(__dirname, '../dist/index.html'),// PathsassetsRoot: path.resolve(__dirname, '../dist'),assetsSubDirectory: 'static',assetsPublicPath: '/',/*** Source Maps*/productionSourceMap: false,devtool: '#source-map',productionGzip: false,productionGzipExtensions: ['js', 'css'],bundleAnalyzerReport: process.env.npm_config_report}}

2、开发环境 config/dev.env.js

保留/api

'use strict'const merge = require('webpack-merge')const prodEnv = require('./prod.env')module.exports = merge(prodEnv, {NODE_ENV: '"development"',API_ROOT:'"/api"'})

3、生产环境config/prod.env.js

去掉api,只要/

'use strict'module.exports = {NODE_ENV: '"production"',API_ROOT: '"/"'}

4、 请求时拼接前缀

// 创建axios实例const service = axios.create({baseURL: process.env.API_ROOT, // api的base_urltimeout: 15000 // 请求超时时间})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。