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] vue在开发过程中要同时跟N个不同的后端人员联调接口(请求的url不一样)时你该怎么办? #341

Open
haizhilin2013 opened this issue Jun 20, 2019 · 3 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

[vue] vue在开发过程中要同时跟N个不同的后端人员联调接口(请求的url不一样)时你该怎么办?

@haizhilin2013 haizhilin2013 added the vue vue label Jun 20, 2019
@Myh-cs
Copy link

Myh-cs commented Jul 9, 2019

webpack 的devServer配置下代理

@sky124380729
Copy link

devServer中把所有的服务人员的地址代理都写进去,
然后动态更改接口的baseUrl,这样切换不同后端人员的时候不用重启

@Cai-zhiji
Copy link

多个环境变量

在Vue项目中,可以配置多个环境变量,每个环境变量对应不同的后端接口地址。你可以在不同的环境中使用不同的环境变量来指定对应的后端接口。
在项目根目录下的.env文件中,可以定义不同的环境变量。例如:

# .env.development
VUE_APP_API_URL=http://dev.backend.com/api

# .env.staging
VUE_APP_API_URL=http://staging.backend.com/api

# .env.production
VUE_APP_API_URL=http://production.backend.com/api

在项目中使用环境变量:

const apiUrl = process.env.VUE_APP_API_URL;
// 使用apiUrl作为请求接口的基础URL

然后,你可以在不同的开发环境中使用不同的环境变量文件,或者在构建时指定不同的环境变量文件,以连接到不同的后端接口。

代理配置

另一种方式是通过配置代理来区分不同的后端接口。在Vue的配置文件(例如vue.config.js)中,可以配置代理规则,将特定的接口请求代理到对应的后端接口。

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://backend1.com',
        changeOrigin: true,
      },
      '/api2': {
        target: 'http://backend2.com',
        changeOrigin: true,
      },
      // 其他代理规则...
    },
  },
};

在代码中发起接口请求时,使用代理的地址作为请求的URL。例如:

axios.get('/api/some-endpoint');
axios.post('/api2/another-endpoint');

根据请求的URL路径,代理会将请求转发到对应的后端接口地址。

通过以上的配置,你可以同时与多个不同的后端人员联调接口,只需切换环境变量或配置不同的代理规则即可连接到不同的后端接口。这样可以方便地进行接口联调和开发工作。

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

No branches or pull requests

4 participants