Skip to content

Commit

Permalink
docs(examples): add vanilla http server example
Browse files Browse the repository at this point in the history
  • Loading branch information
chimurai committed Apr 27, 2024
1 parent 639cfe4 commit 4fab094
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
29 changes: 29 additions & 0 deletions examples/http-server/index.js
@@ -0,0 +1,29 @@
/**
* Module dependencies.
*/
const http = require('node:http');
const { createProxyMiddleware } = require('../../dist'); // require('http-proxy-middleware');

/**
* Configure proxy middleware
*/
const jsonPlaceholderProxy = createProxyMiddleware({
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true, // for vhosted sites, changes host header to match to target's host
logger: console,
});

/**
* Add the proxy to http-server
*/
const server = http.createServer(jsonPlaceholderProxy);

server.listen(3000);

console.log('[DEMO] Server: listening on port 3000');
console.log('[DEMO] Opening: http://localhost:3000/users');

require('open')('http://localhost:3000/users');

process.on('SIGINT', () => server.close());
process.on('SIGTERM', () => server.close());
22 changes: 22 additions & 0 deletions recipes/servers.md
Expand Up @@ -4,6 +4,7 @@ Overview of `http-proxy-middleware` implementation in different servers.

Missing a server? Feel free to extend this list of examples.

- [http.createServer](#httpcreateserver)
- [Express](#express)
- [Connect](#connect)
- [Next.js](#nextjs)
Expand All @@ -16,6 +17,27 @@ Missing a server? Feel free to extend this list of examples.
- [grunt-browser-sync](#grunt-browser-sync)
- [gulp-webserver](#gulp-webserver)

## http.createServer

Vanilla http server implementation with [`http.createServer`](https://nodejs.org/docs/latest/api/http.html#httpcreateserveroptions-requestlistener)

```javascript
const http = require('node:http');
const { createProxyMiddleware } = require('http-proxy-middleware');

/**
* Configure proxy middleware
*/
const apiProxy = createProxyMiddleware({
target: 'http://www.example.com',
changeOrigin: true, // for vhosted sites, changes host header to match to target's host
});

const server = http.createServer(jsonPlaceholderProxy);

server.listen(3000);
```

## Express

https://github.com/expressjs/express
Expand Down

0 comments on commit 4fab094

Please sign in to comment.