webpack-dev-server代理:带通配符的上下文

24

我想将/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
    },
  },
},

但是它不起作用, 输入图像描述


1
你需要把配置放在哪里? - AturSams
3个回答

39

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

在底层webpack-dev-server将所有代理配置传递给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
     }
   }
 },

9
应使用代理选项:changeOrigin: true - chimurai
changeOrigin: true/false, 默认值:false - 将主机头的来源更改为目标URL。是的,它确实起作用。感谢您的回答! - Arthur Xu
我对webpack不熟悉,你在哪里放置代理的配置? - AturSams
1
哪个版本的webpack支持这个代理功能?我正在使用webpack:3.11.1和webpack-dev-server:2.9.6以及http-proxy-middelware:0.19.1。 这个代理配置对我不起作用,我已经尝试了所有可能的代理配置组合。 - Vijender Kumar

10

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

示例:

Webpack devserver代理配置:

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。


1
这对我来说很好用。
    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',
        ...

4
请在您的答复中添加更多信息。一个好的答案更像是代码块。 - live2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接