diff --git a/examples/http-server/index.js b/examples/http-server/index.js new file mode 100644 index 00000000..eb52d553 --- /dev/null +++ b/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()); diff --git a/recipes/servers.md b/recipes/servers.md index 45cb656f..b01480f5 100644 --- a/recipes/servers.md +++ b/recipes/servers.md @@ -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) @@ -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