Skip to content
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

docs(examples): add vanilla http server example #996

Merged
merged 1 commit into from
Apr 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions examples/http-server/index.js
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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