grunt-connect-proxy-mock
给grunt
的Dev Server
提供了
Mock
功能 — 既能mock
普通的Restful API
,也能伪装WebSocket Server
推送ws
假数据。Proxy
功能 — 额外配备了对真实后端响应数据结果集的篡改能力。
的中间件。
用法概述
在npm i -D grunt-connect-proxy-mock
安装之后,不需要显式地向Gruntfile
上下文导入该插件。而仅需向grunt
任务清单插入configureProxyMock
任务。其位置在configureProxies
之后与connect
之前。例如,
grunt.registerTask('serve', function (target) {
grunt.task.run([
'configureProxies:serve',
'configureProxyMock:livereload',
'connect:livereload'
]);
});
在grunt-contrib-connect
插件配置结点connect
下的自定义任务配置子节点内(例如,任务为livereload
的配置结点),添加三个新配置节点webSocketMockRouteRules
,webMockRouteRules
和webProxyRouteRules
。
{
connect: {
livereload: {
webSocketMockRouteRules: [..., {
pathname: string,
onConnection: (ws, wss) => void,
onMessage: (message, ws, wss) => void,
onError: (err, ws, wss) => void
}, ...],
webMockRouteRules: [..., [
method,
pathname,
object | (req, res) => object
], ...],
webProxyRouteRules: [..., [
method,
pathname,
query,
(buffer: Buffer, req, res) => string | Buffer
], ...]
}
}
}
开启Proxy Dev Server
中间件的先决条件
第一,在宿主工程内,与grunt-connect-proxy-mock
依赖项平级安装peer dependency
依赖项grunt-connect-proxy@^0.2.0
。
第二,在connect
中相同的任务配置结点下,给grunt-connect-proxy
插件添加配置结点proxies
{
connect: {
livereload: {
proxies: [..., {
context: string,
host: string,
port: number,
https: boolean
}, ...]
}
}
}
完整的Gruntfile
配置例程
{
connect: {
livereload: {
proxies: [..., {
context: string,
host: string,
port: number,
https: boolean
}, ...],
webSocketMockRouteRules: [..., {
pathname: string,
onConnection: (ws, wss) => void,
onMessage: (message, ws, wss) => void,
onError: (err, ws, wss) => void
}, ...],
webMockRouteRules: [..., [
method,
pathname,
object | (req, res) => object
], ...],
webProxyRouteRules: [..., [
method,
pathname,
query,
(buffer: Buffer, req, res) => string | Buffer
], ...]
}
}
}