Skip to content

Commit 4eeceff

Browse files
author
zhaoxuxu
committed
fix: can not proxy after parse json
check: http-party/node-http-proxy#1279
1 parent 691250a commit 4eeceff

File tree

4 files changed

+35
-7
lines changed

4 files changed

+35
-7
lines changed

package-lock.json

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@badeggg/mock-api",
3-
"version": "0.12.0",
3+
"version": "0.12.1",
44
"description": "mock api",
55
"main": "./src/index.js",
66
"bin": {

src/middlewares/mapToRes/index.js

+27-4
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,38 @@ const matchAProxy404 = require('./matchAProxy404');
44
const httpProxy = require('http-proxy');
55
const proxy = httpProxy.createProxyServer({});
66

7+
function doProxy(req, res, target) {
8+
proxy.once('proxyReq', function (proxyReq, request, response) {
9+
if (!request.body || !Object.keys(request.body).length) {
10+
return;
11+
}
12+
13+
const contentType = proxyReq.getHeader('Content-Type');
14+
const writeBody = (bodyData) => {
15+
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
16+
proxyReq.write(bodyData);
17+
};
18+
19+
if (contentType.includes('application/json')) {
20+
writeBody(JSON.stringify(request.body));
21+
}
22+
23+
if (contentType === 'application/x-www-form-urlencoded') {
24+
writeBody(querystring.stringify(request.body));
25+
}
26+
});
27+
delete req.headers.host;
28+
proxy.web(req, res, {target}, (err) => console.log(err));
29+
}
30+
731
module.exports = function(req, res, next) {
832
matchAResponse(req)
933
.then(
1034
responseFilePath => {
1135
if (!responseFilePath) {
12-
const proxy404 = matchAProxy404(req);
13-
if (proxy404) {
14-
delete req.headers.host;
15-
proxy.web(req, res, {target: proxy404}, (err) => console.log(err));
36+
const proxy404Target = matchAProxy404(req);
37+
if (proxy404Target) {
38+
doProxy(req, res, proxy404Target);
1639
} else {
1740
res.sendStatus(404);
1841
}

src/test/curl

+5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
curl localhost:3000/example/sdfd?sdsd=223 -v
22
curl localhost:3000/404/sdfd?sdsd=223 -v
3+
34
curl localhost:3000/example/sdfd?sdsd=223 -v \
45
-H 'content-type: application/json' \
56
--data '{"username":"xyz","password":"xyz"}'
7+
8+
curl localhost:3000/404/sdfd?sdsd=223 -v \
9+
-H 'content-type: application/json' \
10+
--data '{"username":"xyz","password":"xyz"}'

0 commit comments

Comments
 (0)