【问题标题】:webpack-dev-server proxy: context with wildcardwebpack-dev-server 代理:带通配符的上下文
【发布时间】:2016-08-08 07:22:19
【问题描述】:

我想将 /v1/* 代理到 http://myserver.com,这是我的脚本

devServer: {
  historyApiFallBack: true,
  // progress: true,
  hot: true,
  inline: true,
  // https: true,
  port: 8081,
  contentBase: path.resolve(__dirname, 'public'),
  proxy: {
    '/v1/*': {
      target: 'http://api.in.uprintf.com',
      secure: false
      // changeOrigin: true
    },
  },
},

但它不起作用,

【问题讨论】:

  • 配置需要放在哪里?

标签: webpack http-proxy webpack-dev-server


【解决方案1】:

更新: 感谢@chimurai,设置changeOrigin: true 对使其正常工作很重要。

Underneath webpack-dev-server 将所有代理配置从documentation 传递给http-proxy-middleware。很明显,您想要的用例实际上是通过/v1/** 路径实现的:

devServer: {
   historyApiFallBack: true,
   // progress: true,
   hot: true,
   inline: true,
   // https: true,
   port: 8081,
   contentBase: path.resolve(__dirname, 'public'),
   proxy: {
     '/v1/**': {
       target: 'http://api.in.uprintf.com',
       secure: false,
       changeOrigin: true
     }
   }
 },

【讨论】:

  • 应该使用代理选项:changeOrigin: true
  • changeOrigin: true/false, Default: false - changes the origin of the host header to the target URL 是的,它确实有效。感谢您的回答!
  • 我是 webpack 新手,你把代理的配置放在哪里?
  • 哪个版本的 webpack 支持这个代理功能,我使用的是 webpack: 3.11.1 和 webpack-dev-server: 2.9.6 和 http-proxy-middelware: 0.19.1。这个代理配置不适合我,我已经尝试了代理配置的所有可能组合。
【解决方案2】:

确保您的请求 url 和端口与您的 webpack-dev-server 正在运行的匹配。因此,如果您的 api 位于 http://localhost:5000,并且您的开发服务器在 http://localhost:8080 上运行,请确保您的所有请求都发往 http://localhost:8080。最好将您的请求发送到localhost:8080/api(以避免与应用程序路由冲突)并使用路径重写来删除/api。

示例:

Webpack 开发服务器代理配置:

proxy: {
    '/api': {
        target: 'http://localhost:5000',
        pathRewrite: { '^/api': '' },
    },
}

Webpack 开发服务器运行于:

http://localhost:8080

所需的 API 端点:

http://localhost:5000/items

在您的应用中,发出请求:

http://localhost:8080/api/items.

应该工作。在我看来,以上所有问题都源于向 API url 和端口发出请求,而不是 webpack 开发服务器 url 和端口,并使用代理和路径重写将请求定向到 API。

【讨论】:

    【解决方案3】:

    这对我来说很好。

        devServer: {
            host: '11.11.111.111',          //local ip
            port: 8080,
            contentBase: outputpath,
            historyApiFallback: true,
            inline: true,
            proxy: {
              '/api':{
                    target:'http://example.com',
                    pathRewrite: {'^/api' : ''},
                    secure:false,
                    changeOrigin:true
              }
            }
        },
    

    //使用

        $.ajax({
            url:'/api/pvp/share/getsharecfg.php',
            dataType:'json',
            ...
    

    【讨论】:

    • 请在您的答案中添加更多信息。一个好的答案更像是一个代码块。
    猜你喜欢
    • 2019-10-16
    • 1970-01-01
    • 2017-02-28
    • 2016-07-18
    • 2019-07-08
    • 2015-10-17
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多