Skip to content

Commit 67f485b

Browse files
authored
docs: add proxy example (#3937)
1 parent 2c730a3 commit 67f485b

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

examples/proxy/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# proxy
2+
3+
Proxying some URLs can be useful when you have a separate API backend development server and you want to send API requests on the same domain.
4+
5+
**webpack.config.js**
6+
7+
```js
8+
module.exports = {
9+
// ...
10+
devServer: {
11+
proxy: {
12+
"/proxy": {
13+
target: "http://localhost:5000",
14+
},
15+
},
16+
},
17+
};
18+
```
19+
20+
To run this example use the following command:
21+
22+
```console
23+
npx webpack serve --open
24+
```
25+
26+
## What Should Happen
27+
28+
1. The script start a proxy server on `http://localhost:5000/` and open `http://localhost:8080/` in your default browser.
29+
2. You should see the text on the page itself change to read `Success! Now visit /proxy`.
30+
3. Now visit the `/proxy` route by clicking on the `/proxy` text, you should see the text on the page itself change to read `response from proxy`.

examples/proxy/app.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
"use strict";
2+
3+
const target = document.querySelector("#target");
4+
5+
target.classList.add("pass");
6+
target.innerHTML = "Success! Now visit <a href='/proxy'>/proxy</a>";

examples/proxy/webpack.config.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"use strict";
2+
3+
const express = require("express");
4+
// our setup function adds behind-the-scenes bits to the config that all of our
5+
// examples need
6+
const { setup } = require("../util");
7+
8+
async function listenProxyServer() {
9+
const proxyApp = express();
10+
11+
proxyApp.get("/proxy", (req, res) => {
12+
res.send("response from proxy");
13+
});
14+
15+
await new Promise((resolve) => {
16+
proxyApp.listen(5000, () => {
17+
resolve();
18+
});
19+
});
20+
}
21+
22+
module.exports = setup({
23+
context: __dirname,
24+
entry: "./app.js",
25+
devServer: {
26+
onBeforeSetupMiddleware: async () => {
27+
await listenProxyServer();
28+
},
29+
proxy: {
30+
"/proxy": {
31+
target: "http://localhost:5000",
32+
},
33+
},
34+
},
35+
});

0 commit comments

Comments
 (0)