webpack-dev-server proxy dosen't work

2019-02-12 18:12发布

问题:

I want to proxy /v1/* to http://myserver.com, and here is my script

 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
     }
   }
 },

but it doesn't work,

回答1:

Update: thanks to @chimurai, setting changeOrigin: true is important to make it work.

Underneath webpack-dev-server passes all the proxy configuration to http-proxy-middleware, from the documentation. It's clear the use case you want is actually achieved with /v1/** path:

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
     }
   }
 },


回答2:

Make sure that your request url and port matches that which your webpack-dev-server is running on. So, if your api is located at http://localhost:5000, and your dev server is running on http://localhost:8080, make sure all of your requests are to http://localhost:8080. Its best to make your requests to localhost:8080/api (to avoid conflict with app routes) and use the path rewrite to remove the /api.

Example:

Webpack devserver proxy config:

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

Webpack dev server running on:

http://localhost:8080

Desired API endpoint:

http://localhost:5000/items

In your app, make the request to:

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

This should work. It seems to me that all of the above issues stem from making the request to the API url and port rather than the webpack dev server url and port and using the proxy and path rewrite to direct the request to the API.



回答3:

This works fine for me.

    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
          }
        }
    },

//use

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