使用 vue-cli 将请求代理到单独的后端服务器

Proxy requests to a separate backend server with vue-cli

我正在使用 vue-cli webpack-simple 模板生成我的项目,我想将请求代理到一个单独的后端服务器。这怎么能轻易实现呢?

如果您将 webpack 模板与 vue-cli 一起使用,那么您可以在此参考文档中找到所需的信息:

http://vuejs-templates.github.io/webpack/proxy.html

或者现在不更改模板,您可以将相关配置从 webpack 模板复制到本地 webpack-simple 模板。

编辑:更多信息来自我的本地设置

这是我在 module.exports 下的 config/index.js 中的内容:

dev: {
    env: require('./dev.env'),
    port: 4200,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/api': {
            target: 'http://localhost:8080',
            changeOrigin: true
        },
        '/images': {
            target: 'http://localhost:8080',
            changeOrigin: true
        },
        // and so on...

上面的配置 运行 我的 vue-cli 在端口 4200 上,我 运行 我的服务器在端口 8080 上。

编辑:在评论 #4 和 #5

后更正了关于 CORS 的信息

注:

  • dev.proxyTable 中的 changeOrigin 选项(在 webpack 配置中)确保您不需要在服务器 API 响应上提供 CORS headers。
  • 如果您出于任何原因决定省略 changeOrigin,那么您需要确保您的服务器 API 在其响应 headers 中包含 Access-Control-Allow-Origin: *(或等效) .

参考文献:

  1. https://whosebug.com/a/36662307/654825
  2. https://github.com/chimurai/http-proxy-middleware

@vue/cli3.x:

  • 在项目的 root 文件夹中创建一个 vue.config.js 文件,如果您还没有的话。
  • 其内容如下:
// vue.config.js
module.exports = {
  devServer: {
    proxy: {
      "/gists": {
        target: "https://api.github.com",
        secure: false
      }
    }
  }
};

现在任何对(假设您的开发服务器位于 localhost:8080http://localhost:8080/gists 的调用都将被重定向到 https://api.github.com/gists


另一个例子:代理所有呼叫

假设您有一个通常部署在 localhost:5000 的本地后端服务器,您希望将对 /api/anything 的所有调用重定向到它。使用:

// vue.config.js
module.exports = {
    devServer: {
        proxy: {
            "/api/*": {
                target: "http://localhost:5000",
                secure: false
            }
        }
    }
};
module.exports = {

    devServer: {
        proxy: {
            '/api': {
                target: 'http://genius.net',
                changeOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            },
            '/auth': {
                target: 'http://genius23.net',
                changeOrigin: true,
                pathRewrite: {
                    '^/auth': ''
                }
            },
        }
    }

};