What is @types/http-proxy-middleware?
@types/http-proxy-middleware provides TypeScript type definitions for the http-proxy-middleware package, which is used to create a proxy middleware for connecting, redirecting, and modifying HTTP requests in a Node.js application.
What are @types/http-proxy-middleware's main functionalities?
Basic Proxy Setup
This feature allows you to set up a basic proxy middleware that forwards requests from '/api' to 'http://www.example.org'. The 'changeOrigin' option modifies the origin of the host header to the target URL.
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true });
module.exports = function(app) {
app.use(apiProxy);
};
Path Rewriting
This feature allows you to rewrite the URL path before forwarding the request. In this example, requests to '/api' will be forwarded to 'http://www.example.org' with the '/api' prefix removed.
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware('/api', {
target: 'http://www.example.org',
pathRewrite: { '^/api': '' },
changeOrigin: true
});
module.exports = function(app) {
app.use(apiProxy);
};
Custom Proxy Configuration
This feature allows you to customize the proxy request by adding custom headers or modifying the request in other ways. In this example, a custom header 'X-Special-Proxy-Header' is added to the proxied request.
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware('/api', {
target: 'http://www.example.org',
changeOrigin: true,
onProxyReq: (proxyReq, req, res) => {
// Add custom header to request
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
}
});
module.exports = function(app) {
app.use(apiProxy);
};
Other packages similar to @types/http-proxy-middleware
http-proxy
http-proxy is a library for creating HTTP proxies in Node.js. It provides a lower-level API compared to http-proxy-middleware, giving you more control over the proxying process but requiring more setup and configuration.
express-http-proxy
express-http-proxy is a simpler alternative to http-proxy-middleware for proxying HTTP requests in an Express application. It offers a more straightforward API but with fewer customization options compared to http-proxy-middleware.
node-http-proxy
node-http-proxy is another library for creating HTTP proxies in Node.js. It is similar to http-proxy but offers additional features like WebSocket proxying and more detailed event handling.