How do I change path on the target?
Problem
For example, my request is http://localhost/this/that/path and on the target, I want http-proxy to call the target like this http://target.server/final/path. If you noticed the `this/that` got replaced by `final` [code block]
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Configure HTTP Proxy Path Rewriting
The HTTP proxy is not configured to rewrite the incoming request path to the desired target path. This results in the request being sent to the target server with the original path instead of the modified one.
Awaiting Verification
Be the first to verify this fix
- 1
Install http-proxy-middleware
Ensure that you have the http-proxy-middleware package installed in your Node.js application. This package allows for easy path rewriting.
bashnpm install http-proxy-middleware - 2
Set Up Proxy Middleware
In your Node.js application, set up the proxy middleware to intercept requests and rewrite the path accordingly.
javascriptconst { createProxyMiddleware } = require('http-proxy-middleware'); app.use('/this/that', createProxyMiddleware({ target: 'http://target.server', pathRewrite: {'^/this/that': '/final/path'}, changeOrigin: true, })); - 3
Test the Proxy Configuration
Make a request to the original path and check if it is correctly proxied to the target server with the new path.
bashcurl http://localhost/this/that/path - 4
Check Target Server Response
Verify that the target server responds correctly to the proxied request. You should see the expected response from http://target.server/final/path.
bashcurl http://target.server/final/path
Validation
Confirm that requests to http://localhost/this/that/path are successfully redirected to http://target.server/final/path and that the expected response is returned.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep