Skip to content

webpack-dev-server proxy dosen't work #458

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

Closed
Authorlove opened this issue Apr 19, 2016 · 39 comments
Closed

webpack-dev-server proxy dosen't work #458

Authorlove opened this issue Apr 19, 2016 · 39 comments

Comments

@Authorlove
Copy link

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

 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 results in 404 not found error, and here is the response,

Request URL:http://localhost:8080/v1/address/school?keyword=scut&_=1460968888999
Request Method:GET
Status Code:404 Not Found
Remote Address:127.0.0.1:8080
Response Headers
view source
connection:close
content-encoding:gzip
content-type:text/html
date:Mon, 18 Apr 2016 08:41:34 GMT
server:nginx/1.4.6 (Ubuntu)
transfer-encoding:chunked
X-Powered-By:Express

It seems to proxy to my ubuntu nginx server, since i use mac os locally, but i don't use express in my remote server.

@Authorlove
Copy link
Author

when i set proxy option: changeOrigin: true, it works.
From the node-http-proxy's document, it says,
'changeOrigin: true/false, Default: false - changes the origin of the host header to the target URL'. Does the changeOrigin option depend on the remote backend server framework?

@MikaAK
Copy link

MikaAK commented Apr 21, 2016

@Authorlove try

proxy: [{
      path: `/v1/*`,
      target: 'http://api.in.uprintf.com'
}],

@MarkPieszak
Copy link

Have you had any luck getting HMR to work through a proxy? I kept noticing HMR was still sending through the original port when I tried this :(

@fractalf
Copy link

+1
Can't get proxy to work, no matter what i put in proxy options.

Server.js:

options.proxy.forEach(function (proxyOptions) {
    proxyOptions.ws = proxyOptions.hasOwnProperty('ws') ? proxyOptions.ws : true;
    app.all(proxyOptions.path, function (req, res, next) {
        var bypassUrl = typeof proxyOptions.bypass === 'function' ? proxyOptions.bypass(req, res, proxyOptions) : false;
        if (bypassUrl) {
            req.url = bypassUrl;
            next();
        } else {
            if(typeof proxyOptions.rewrite === 'function') proxyOptions.rewrite(req, proxyOptions);
            if (proxyOptions.host) {
                req.headers.host = proxyOptions.host;
            }
            proxy.web(req, res, proxyOptions, function(err){
                var msg = "cannot proxy to " + proxyOptions.target + " (" + err.message + ")";
                this.sockWrite(this.sockets, "proxy-error", [msg]);
                res.statusCode = 502;
                res.end();
            }.bind(this));
            if (proxyOptions.configure) {
                proxyOptions.configure(proxy);
            }
        }
    }.bind(this));
}.bind(this));

The code inside app.all doesn't seem to run at all..
Would be great with a working example

@busbyk
Copy link

busbyk commented Apr 29, 2016

I'm experiencing a potentially related issue. I'm trying to use the rewrite option and the function I pass it does not seem to fire. I tested the code separately to make sure the function wasn't just working incorrectly and the code works.

If the above comment is true and the code inside of app.all isn't firing that would explain my issue. But, definitely not ideal...

@Authorlove
Copy link
Author

Because I use nginx as my server, it needs Host header filed, so when i set changeOrigin: true, it works. And my case is done.

@vinhlh
Copy link

vinhlh commented May 15, 2016

Yo guys, let's try to change * to **. It works for me with latest webpack-dev-server (latest commit).
Check wildcard path matching section in https://github.com/chimurai/http-proxy-middleware

@KingScooty
Copy link

@vinhlh this saved me! Wish there was an upgrade doc for webpack 2.0.

@ljwagerfield
Copy link

@vinhlh also worked for me.

Neither of the following worked:
proxy: {'*': 'http://localhost:3000'}
contentBase: {target: 'http://localhost:3000'}

But this does: proxy: {'**': 'http://localhost:3000'}

👍

@zbowhay
Copy link

zbowhay commented Aug 22, 2016

May be helpful for some,
I was able to get my proxy to a express server by using this config:
proxy:{ '/api/**': { target: 'http://localhost:4001', secure: false } }

in my case adding http:// and /** resolved my issues.

@SpaceK33z
Copy link
Member

@Authorlove can this be closed?

@pgangwani
Copy link

pgangwani commented Aug 30, 2016

Although this is closed issue, Need some guidance.

I dont know how much I am screwing up. Can any one of you help me in my configuration, I wish to
proxy all "/api/**" request to "jsonplaceholder.typicode.com". For example: "localhost:3001/api/users/1" to "jsonplaceholder.typicode.com/users/1"
My configurations :
proxy: { '/api/**': { target: { 'host': 'jsonplaceholder.typicode.com', 'port': 80, 'protocol': 'http:' }, secure: false, changeOrigin: true, pathRewrite: { '^/api': '' } }

I am just suferring from trail of 404s.
Kindly response if you can identify the issue.

@SpaceK33z
Copy link
Member

@pgangwani, Did you try without the trailing slash in /api/ (so /api)? In all the examples in http-proxy-middleware, I see they do it like that, so it could be that with the trailing slash it only proxies if the url has a exact match.

@pgangwani
Copy link

That returns 404 .
I guess same path is passed to target path '/api' should be removed before sending to target.
Any configuration ?

@SpaceK33z
Copy link
Member

@pgangwani, yeah pathRewrite is for that, but you already have that in your config. Are you using [email protected]?

@pgangwani
Copy link

No. [email protected]

@pgangwani
Copy link

Can any one else help?

@bivvo
Copy link

bivvo commented Aug 31, 2016

@pgangwani
Try this. Was able to get this to run.

proxy:{
      '/api/*' : {
        target: 'http://jsonplaceholder.typicode.com/', 
        changeOrigin: true,
        pathRewrite: {
        '^/api': ''
        }
      }
    }

@pgangwani
Copy link

Not working.
I think there is some other issue not a configuration.

On Sep 1, 2016 12:10 AM, "Brad J" [email protected] wrote:

@pgangwani https://github.com/pgangwani
Try this. Was able to get this to run.

proxy:{
'/api/*' : {
target: 'http://jsonplaceholder.typicode.com/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
#458 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/ANpzLHgauP9vG0QaiZtFeD4WW4NmGX3Oks5qlcqBgaJpZM4IKlqv
.

@BrendanDougan
Copy link

BrendanDougan commented Sep 1, 2016

My config has stopped working after 6 months on an npm install.
webpack-dev-server 1.15.0 is version

Reverting to 1.14.1 fixed the issue

@SpaceK33z
Copy link
Member

@pgangwani, I copy/pasted @bivvo's code in the example/webpack.config.js of this repo to test this, and then browsed to http://localhost:8080/api/users. It worked. With what url are you testing this?

@johnelliott
Copy link

Thanks @vinhlh.

For others fiddling with this, here's what I ended up with to get hot module reloading working and still able to hit my API server:

I began here: https://github.com/chimurai/http-proxy-middleware#context-matching, looking at pattern matching:

  • wildcard path matching

For fine-grained control you can use wildcard matching. Glob pattern matching is done by micromatch. Visit micromatch or glob for more globbing examples.

Initially it appeared that I could specify a quoted array as the key for the proxy property of the webpack config e.g. "['/a', '/b']": {target, secure, etc} to match /a and /b/, but this turned out not to be the case and brace expansion was the way.

My solution was just to use whatever bits of the glob library would work in the webpack config. In https://www.npmjs.com/package/glob#glob-primer I used two things, the ! and the {} brace expansion.

{} brace expansion:

!/**/*.css
!/**/*.js
!/**/*.hot-update.json

Then, according to the glob docs:

!(pattern|pattern|pattern) Matches anything that does not match any of the patterns provided.

So any path not ending in these three extensions would match and thus be proxied.

  devServer: {
    // progress: true,
    hot: true,
    inline: true,
    // https: true,
    // port: 8081,
    contentBase: path.resolve(__dirname,'public'),
    proxy: {
      '!/**/*.{css,js,hot-update.json}': {
        target: 'http://localhost:3000',
        secure: false
        // changeOrigin: true
      }
    }
  },

There's surely a better way, but this is working for now.

@zcoding
Copy link

zcoding commented Oct 12, 2016

[email protected]

{"changeOrigin": true}

works for me

@rajaram-g
Copy link

rajaram-g commented Nov 14, 2016

webpack-dev-server: 2.1.0-beta.9, webpack: 2.1.0-beta.25 and express for backend api server

Objective is to redirect api requests from localhost:3000/api/* to localhost:3030/*. Followed the example in this repository as @SpaceK33z suggested.

It worked for me with the following config (pathRewrite) :

        proxy: {
        "/api/**": {
        target: "http://localhost:3030/",
        pathRewrite: {
                    "^/api": ""
                }
      }

@rmi7 rmi7 mentioned this issue Nov 15, 2016
@mrsufgi
Copy link

mrsufgi commented Nov 26, 2016

@mproid that config worked for me too!

var apiProxy = proxy('/api/**', {
    target: 'https://api.instagram.com/v1/',
    pathRewrite: {
      "^/api": ""
    },
    changeOrigin: true,
    logLevel: 'debug',
  });

pathRewrite is a must here since we don't wont to prefix requests with an actual '/api'
Thanks

@YuyangWitness
Copy link

@bivvo
Thank you very much, I have solved this problem finally.
when I add pathRewrite, this problem was solved!!!

@erosenberg
Copy link

erosenberg commented Aug 25, 2017

I'm unable to get any of these options to work 👎
My main server that serves HTML/ejs is: localhost:3000
My webpack-dev-server is localhost:9000

Here is my config at the moment:

const DEV_SERVER_PORT = 9000;
const DEV_HOST = 'http://localhost';

const config = _.merge(baseConfig, {
  entry: {
    bundle: [
      `webpack-dev-server/client?${DEV_HOST}:${DEV_SERVER_PORT}`,
      'webpack/hot/only-dev-server',
      'react-hot-loader/patch',
      paths.indexPath,
    ],
  },
  output: {
    filename: 'bundle.js',
    path: paths.buildPath,
    publicPath: '/static/build/',
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: [paths.nodeModulesPath],
      loader: 'babel-loader',
    }],
  },
  devtool: 'eval-source-map',
  devServer: {
    contentBase: paths.buildPath,
    // publicPath: `http://lopcalhost:3000/${path.buildPath}`,
    publicPath: '/static/build/',
    hot: true,
    host: '0.0.0.0',
    port: DEV_SERVER_PORT,
    historyApiFallback: true,
    proxy: {
      // '/static/build/**': 'http://[::1]:3000/static/build',
      '**': 'http://[::1]:3000/static/build',
      secure: false,
      changeOrigin: true,
    },
  },
  resolve: {
    extensions: ['.js', '.json'],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(paths.staticPath, 'index.ejs'),
    }),
  ],
});

My HTML markup contains a script tag that is looking for a local bundle.js file.

<script src="/static/build/bundle.js"></script>

What I would like and expect to happen is when I go to request localhost:9000/static/build/bundle.js/ I am proxied to localhost:3000/static/build/bundle.js.

What am I missing here? I'm also using the following:

OSX
"webpack": "^3.5.5",
"webpack-dev-server": "^2.7.1",
npm v5.3.0
node v8.4.0

and the exact error I'm getting is:

[HPM] Error occurred while trying to proxy request /static/build/bundle.js from localhost:9000 to http://[::1]:5000/ (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

EDIT: I think I was expecting the opposite behavior for some weird reason. By proxying the web server through the dev server, I should still be using the dev server, not the actual server while developing.

@granmoe
Copy link

granmoe commented Sep 12, 2017

I've tried every combination here and none are working for me. Here's my config:

const webpack = require("webpack");
const path = require("path");

const IS_DEV = process.env.NODE_ENV === "development";

module.exports = {
	devtool: IS_DEV ? "inline-source-map" : "eval",
	entry: "./src/index.js",
	output: {
		filename: "app.js",
		path: path.resolve(__dirname, "dist")
	},
	resolve: {
		modules: [
			path.resolve(__dirname, "src"),
			"node_modules"
		],
		extensions: [".json", ".js"]
	},
	module: {
		rules: [
			{
				test: /\.html$/,
				exclude: /node_modules/,
				loader: "ractive-loader"
			}, {
				test: /\.js$/,
				exclude: /node_modules/,
				loader: "babel-loader"
			}, {
				test: /\.css$/,
				exclude: /node_modules/,
				loaders: [
					"style-loader",
					"css-loader"
				]
			}
		]
	},
	devServer: {
		contentBase: "./dist",
		hot: true,
		proxy: {
			"/ext_api/**": {
				target: "http://foo.bar/" // obscured to hide my employer
			}
		}
	},
	plugins: [new webpack.HotModuleReplacementPlugin()]
};

The response is a 502, cannotconnect

@tarunjuneja
Copy link

tarunjuneja commented Oct 27, 2017

Just to be explicit - In my case mistakenly i have placed proxy at the root however i was suppose to keep it in devServer

here is my final configuration

devServer: {
    outputPath: path.join(__dirname, "dist"),
    historyApiFallback: true,
    stats: "minimal",
    proxy: {
      "/rest/**":  {
        target: "https://10.98.0.1/",
        secure: false
      }
    },    
  }

@anson-GH
Copy link

anson-GH commented Jul 6, 2018

npm install webpack -g
npm install vue-cli -g
npm install
npm run dev

after run these restart your pc, sometimes need to fresh all again.

@luddensdesir
Copy link

luddensdesir commented Jul 10, 2018

Ugh. None of this works:

  devServer: {
    index: '', // specify to enable root proxying
    host: '...',
    contentBase: '...',
    proxy: {
      '/api': {
        context: () => true,
        target: 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: {
        '^/api': ''
        },
        secure: false
      }
   },

The front end is at 8080 and the server at 3000. No combination of any of the suggestions have worked. Why is this so dinky?

@johnelliott
Copy link

johnelliott commented Jul 10, 2018

@luddens what are you trying to do here?

This is more a matter of understanding and configuring https://github.com/chimurai/http-proxy-middleware than anything about webpack or this dev server. Here under path matching I see something similar to your example with /api. For me, the quickest way forward was trying lots of things—even ones that seemed a bit silly—to understand how it all worked before going to my particular problem.

@wulichenyang
Copy link

Got the same problem. I solved this by removing setting of allowing CORS from the server and it works for me.

@davidgolden
Copy link

@wulichenyang Yep that did it for me.

Removed app.all('/', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); from my server.js

My webpack config looks like this:
proxy: { '/api': { target: 'http://localhost:5000', pathRewrite: {'^/api': ''}, } }

I'm on webpack-dev-server version 3.2.1

@imzubair10
Copy link

This should work:

devServer: {
    contentBase: path.join(__dirname, "/dist"),
    historyApiFallback: true,
    publicPath: '/',
    inline: true,
    port: 8080,
    stats: { colors: true },
    hot: true,
    proxy: {
      '/api/**': {
        target: 'http://localhost:44310',
        pathRewrite: { '^/api': '' },
        secure: false,
        changeOrigin: true
      }
    }
}

@Jammmes
Copy link

Jammmes commented Jun 30, 2020

Hi @pgangwani! If you resolved this issue, could you show me the solution, please?

@tarunjuneja
Copy link

tarunjuneja commented Jun 30, 2020 via email

@Jammmes
Copy link

Jammmes commented Jul 2, 2020 via email

@amustapha
Copy link

amustapha commented Jul 11, 2021

I'm also having this trouble...

devserver: {
  proxy: {
    '/': 'https://app.staging.com',
    changeOrigin: true
  }
}

But I still get DEPTH_ZERO_SELF_SIGNED_CERT

But, then when I run the backend code locally and use, it works.

devserver: {
  proxy: {
    '/': 'http://localhost:3000'
  }
}

I want to be able to work on the frontend without having to always spin up the server

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

No branches or pull requests