webpack-dev-server proxy dosen't work

Created on 19 Apr 2016  Â·  38Comments  Â·  Source: webpack/webpack-dev-server

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.

Most helpful comment

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?

All 38 comments

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?

@Authorlove try

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

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 :(

+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

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...

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.

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

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

@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'}

👍

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.

@Authorlove can this be closed?

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.

@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.

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

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

Can any one else help?

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

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

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
https://github.com/webpack/webpack-dev-server/issues/458#issuecomment-243859936,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ANpzLHgauP9vG0QaiZtFeD4WW4NmGX3Oks5qlcqBgaJpZM4IKlqv
.

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

@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?

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.

[email protected]

{"changeOrigin": true}

works for me

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": ""
                }
      }

@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

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

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.

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

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

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.

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?

@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.

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

@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

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

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

Hey what's the version of webpack you are using.
I would say answer will depend on that.

Get Outlook for Androidhttps://aka.ms/ghei36


From: Eugen notifications@github.com
Sent: Tuesday, June 30, 2020 11:02:21 AM
To: webpack/webpack-dev-server webpack-dev-server@noreply.github.com
Cc: Tarun Juneja tarun_juneja@hotmail.com; Comment comment@noreply.github.com
Subject: Re: [webpack/webpack-dev-server] webpack-dev-server proxy dosen't work (#458)

Hi @pgangwanihttps://github.com/pgangwani! If you resolved this issue, could you show me the solution, please?

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHubhttps://github.com/webpack/webpack-dev-server/issues/458#issuecomment-651549187, or unsubscribehttps://github.com/notifications/unsubscribe-auth/ABQQYCHNQ3R4RUXIPLXWQMDRZF2GLANCNFSM4CBKLKXQ.

Hi,
I'm using webpack v. 4.35.3
webpack-dev-server v. 3.7.2

,Regards
Evgenii Verhinin

On Tue, Jun 30, 2020, 6:38 PM Tarun Juneja notifications@github.com wrote:

Hey what's the version of webpack you are using.
I would say answer will depend on that.

Get Outlook for Androidhttps://aka.ms/ghei36


From: Eugen notifications@github.com
Sent: Tuesday, June 30, 2020 11:02:21 AM
To: webpack/webpack-dev-server webpack-dev-server@noreply.github.com
Cc: Tarun Juneja tarun_juneja@hotmail.com; Comment <
[email protected]>
Subject: Re: [webpack/webpack-dev-server] webpack-dev-server proxy dosen't
work (#458)

Hi @pgangwanihttps://github.com/pgangwani! If you resolved this issue,
could you show me the solution, please?

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub<
https://github.com/webpack/webpack-dev-server/issues/458#issuecomment-651549187>,
or unsubscribe<
https://github.com/notifications/unsubscribe-auth/ABQQYCHNQ3R4RUXIPLXWQMDRZF2GLANCNFSM4CBKLKXQ

.

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/webpack/webpack-dev-server/issues/458#issuecomment-651835901,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AHKZQ3ELFLEGDCPAUO24HL3RZH2HBANCNFSM4CBKLKXQ
.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mrdulin picture mrdulin  Â·  3Comments

wojtekmaj picture wojtekmaj  Â·  3Comments

da2018 picture da2018  Â·  3Comments

tulika21-zz picture tulika21-zz  Â·  3Comments

StephanBijzitter picture StephanBijzitter  Â·  3Comments