How to solve the uniapp H5 local proxy to achieve cross-domain access?
1. The first solution:
Create a vue.config.js file directly, configure devServer in it, upload the code directly, restart and run the project
Pro test is effective
// vue.config.js
module.exports = {
transpileDependencies: ['uview-ui'],
devServer: {
proxy: {
'/api': {
target: 'https://rivtrust.jz-xxx.xyz/',
changeOrigin: true,
pathRewrite: {
'^/apih5': ''
}
}
},
}
}
2. The second solution:
Find the mainfest.json file in the src directory, modify the file, click "Source View" to see h5
Note: If you do not find the configuration about h5 after opening the "source view", you can click "h5 configuration" and modify the configuration casually, such as setting the page title; after opening the "source view", the h5 configuration will appear configuration.
// manifest.json
{
"h5": {
"devServer": {
"proxy": {
'/api': {
target: 'https://rivtrust.jz-xxx.xyz/',
changeOrigin: true,
pathRewrite: {
'^/apih5': ''
}
}
}
}
}
}
Write this when calling the interface:
Note ⚠️The above two solutions cannot be used at the same time; the second solution will override the first solution
3. There is also a configuration that does not need to be configured:
Use the built-in browser of HBuilder X, there is no cross-domain problem, it is recommended to use
Referenced Articles: Thanks to the following authors
How to solve the problem of reuni-app stepping pit + minor transformation - Nuggets
Solve the cross-domain problem of uniapp H5 terminal (proxy) - Kuxia Muhe's Blog - CSDN Blog
What is cross-domain | uni-app official website
Precautions for using the H5 version of uni-app - DCloud Answers
Configure environment variables:
There are three main ways to configure environment variables in the uni-app project:
uni-app
You can process.env.NODE_ENV
judge whether the current environment is a development environment or a production environment. It is generally used for dynamic switching between connecting to a test server or a production server.
- In HBuilderX, the code compiled by clicking "Run" is the development environment, and the code compiled by clicking "Release" is the production environment
- In the cli mode, it is the common compilation environment processing method.
if (process.env.NODE_ENV === 'development') {
console.log('开发环境');
} else {
console.log('生产环境');
}
Several environment variables are as follows:
Reference article: