Skip to content

Commit

Permalink
Add request forwarding to mock
Browse files Browse the repository at this point in the history
  • Loading branch information
yesmeck committed Mar 17, 2017
1 parent ccc16c3 commit d181c07
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ export default {

// 支持自定义函数,API 参考 express@4
'POST /api/users/create': (req, res) => { res.end('OK'); },

// Forward 到另一个服务器
'GET /assets/*': 'https://assets.online/',

// Forward 到另一个服务器,并指定子路径
// 请求 /someDir/0.0.50/index.css 会被代理到 https://g.alicdn.com/tb-page/taobao-home, 实际返回 https://g.alicdn.com/tb-page/taobao-home/0.0.50/index.css
'GET /someDir/(.*)': 'https://g.alicdn.com/tb-page/taobao-home',
};
```

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"css-loader": "^0.26.1",
"detect-port": "^1.0.7",
"explain-error": "^1.0.3",
"express-http-proxy": "^0.11.0",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.9.0",
"filesize": "^3.3.0",
Expand Down
35 changes: 29 additions & 6 deletions src/utils/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import fs from 'fs';
import assert from 'assert';
import chokidar from 'chokidar';
import chalk from 'chalk';
import proxy from 'express-http-proxy';
import url from 'url';
import { join } from 'path';
import getPaths from '../config/paths';

let error = null;
Expand Down Expand Up @@ -44,6 +47,17 @@ function createMockHandler(method, path, value) {
};
}

function createProxy(method, target) {
return proxy(target, {
filter(req) {
return method ? req.method.toLowerCase() === method.toLowerCase() : true;
},
forwardPath(req) {
return join((url.parse(target).path), req.baseUrl);
},
});
}

export function applyMock(devServer) {
const realRequire = require.extensions['.js'];
try {
Expand Down Expand Up @@ -83,13 +97,22 @@ function realApplyMock(devServer) {
`method of ${key} is not valid`,
);
assert(
typeof config[key] === 'function' || typeof config[key] === 'object',
`mock value of ${key} should be function or object, but got ${typeof config[key]}`,
);
app[keyParsed.method](
keyParsed.path,
createMockHandler(keyParsed.method, keyParsed.path, config[key]),
typeof config[key] === 'function' ||
typeof config[key] === 'object' ||
typeof config[key] === 'string',
`mock value of ${key} should be function or object or string, but got ${typeof config[key]}`,
);
if (typeof config[key] === 'string') {
app.use(
keyParsed.path,
createProxy(keyParsed.method, config[key]),
);
} else {
app[keyParsed.method](
keyParsed.path,
createMockHandler(keyParsed.method, keyParsed.path, config[key]),
);
}
});

// 调整 stack,把 historyApiFallback 放到最后
Expand Down

0 comments on commit d181c07

Please sign in to comment.