This article mainly introduces the method of selecting baseurl in vue.js according to the code running environment. Now I will share it with you and give you a reference.
Configuring a common API prefix can better obtain data locally through interface proxy forwarding, or do a reverse proxy in Nginx during deployment. However, once the project involves a large number of parts that require file upload (file upload does not Taking the Ajax method), we need to consider the baseURL of the better management interface. Ajax requests in the project use axios. The original code is as follows
Before modification
// 创建axios实例、配置baseURL、超时时间 const service = axios.create({ baseURL: '/development/api', // 从环境进程中根据运行环境获取的api的base_url timeout: 5000 // 请求超时时间 })
/* 保存分配角色 */ export function fetchSaveDisUser (params1) { return fetch({ url: '/user/empower', method: 'post', params: params1, paramsSerializer: function (params) { return Qs.stringify(params, { arrayFormat: 'repeat' }) } }) } /* 上传文件URL 从运行环境process.env中读取API配置 */ export let uploadUrl = '/development/api/doi/analys/upload'
Optimization method
Find config/dev.env.js and config/prod.env.js, add the variable API_BASEURL (name customization) in the code as follows:
module.exports = { NODE_ENV: '"production"', // PS:不要复制、开发环境和生产环境有区别 API_BASEURL: '"/development/api/"' // 需要自己添加的代码 }
Then replace baseURL where you need to use it. process.env. API_BASEURL
The modified code is as follows
// 创建axios实例、配置baseURL、超时时间 const service = axios.create({ baseURL: process.env.API_BASEURL, // 从环境进程中根据运行环境获取的api的base_url timeout: 5000 // 请求超时时间 })
/* 保存分配角色 */ export function fetchSaveDisUser (params1) { return fetch({ url: '/user/empower', method: 'post', params: params1, paramsSerializer: function (params) { return Qs.stringify(params, { arrayFormat: 'repeat' }) } }) } /* 上传文件URL 从运行环境process.env中读取API配置 */ export let uploadUrl = process.env.API_BASEURL + '/doi/analys/upload'
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Explain in detail how to use this in React components.
How to use TypeScript methods in Vue components (detailed tutorial)
Implement one-way binding in the vue component passing object. How to do it?
The above is the detailed content of How to select baseurl in vue.js. For more information, please follow other related articles on the PHP Chinese website!