venus.config.js
const { join } = require('path');
const { tcAppRespJson, resJsonWrap } = require('venus-mock');
module.exports = {
babel: {},
rollupAlias: {},
appSecret: '9421B33C-E398-4039-87E8-B46DC3C26E74',
mockOption: {
port: 3001,
hostname: 'mock.venus.org',
baseDir: join(__dirname, 'mocks'),
staticDirs: [{ prefix: '/static', dir: join(__dirname, 'mocks/statics') }],
routeDefs: {
'/route': { defs: ['routeApi'], middlewares: [tcAppRespJson] }
},
restDefs: {
'/rest': { defs: ['restApi'], middlewares: [resJsonWrap] },
'/intergrationsvc': { defs: ['thirds'], middlewares: [] },
}
},
mockProxy: {
'/api': {
target: `http://mock.venus.org:${3001}/routeApi`,
onProxyReq(proxyReq, req) {
if (req.method === 'POST' && req.body) {
// modify the request. Here i just by removed ip field from the request you can alter body as you want
const bodyData = JSON.stringify(req.body);
// in case if content-type is application/x-www-form-urlencoded -> we need to change to application/json
proxyReq.setHeader('Content-Type', 'application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
// stream the content
proxyReq.write(bodyData);
}
}
}
}
};
自定义header
const { set } = require('lodash');
module.exports = {
'/rest_home_center': function (req, res) {
set(res, 'response.header', {
"rspType": "0",
"rspCode": "0001",
"rspDesc": "已经是最新版本",
"rspTime": "1556435369155",
});
res.json({
code: '0000',
message: 'result home center',
data: null
});
}
}
自定义mock图片资源
const { set } = require('lodash');
module.exports = {
'/rest_home_center': function (req, res) {
const staticHostUri = req.app.get('hostUri');
res.json({
code: '0000',
message: 'result home center',
data: `${staticHostUri}/static/mock-test.jpg`,
});
}
}
自定义Middleware
const { resJsonWrap } = require('venus-mock');
const customRespJson = resJsonWrap((rawBody, res, req) => {
return rawBody;
});
};
restDefs: {
'/rest': { defs: ['restApi'], middlewares: [customRespJson] },
}