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

add a showcase how to proxy POST with a body #1629

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,42 @@ http.createServer(function (req, res) {

**[Back to top](#table-of-contents)**

#### Forward POST requests with a json body

```ts
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import { IncomingMessage, ServerResponse } from 'http'; import * as httpProxy from 'http-proxy';

add this to the first

const proxy = httpProxy.createProxyServer({
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before the const proxy = httpProxy.createProxyServer create an interface interface ExtendedIncomingMessage extends IncomingMessage { body?: any; rawBody?: Buffer | string; }

the reason to create this interface is to typeScript will catch errors if you try to access properties that don't exist. and to make it runtime error free

target: `http://localhost:3002`
})

proxy.on('proxyReq', (proxyReq, req, res, options) => {
// @ts-expect-error
if (req.body) {
// @ts-expect-error
let bodyData = req.rawBody
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unsafe access to req.rawBody

proxyReq.setHeader('Content-Type', 'application/json')
// proxyReq.setHeader('Content-Type', 'application/x-www-form-urlencoded');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))

proxyReq.write(bodyData)
}
})


```
then somewhere in your HTTP handler
```ts
proxy.web(
req,
res,
{
timeout: 1000 * 60 * 5 // 5 minutes
},
next
)
```

**[Back to top](#table-of-contents)**

#### Using HTTPS
You can activate the validation of a secure SSL certificate to the target connection (avoid self-signed certs), just set `secure: true` in the options.

Expand Down