UNPKG

1.5 kBJavaScriptView Raw
1/*!
2 * MOCK数据服务器
3 * https://github.com/hai2007/mock-server
4 *
5 * author hai2007 < https://hai2007.gitee.io/sweethome >
6 *
7 * Copyright (c) 2021 hai2007 走一步,再走一步。
8 * Released under the MIT license
9 */
10
11const http = require('http');
12const log = require('@hai2007/nodejs').log;
13const fs = require('fs');
14const path = require('path');
15const Mock = require('mockjs')
16
17const jsonfile = JSON.parse(fs.readFileSync(path.join(__dirname, './package.json')));
18
19module.exports = function (config) {
20
21 const port = 'port' in config ? config.port : 8080; // 端口号
22
23 http.createServer(function (request, response) {
24
25 let resultData = config.handler({
26
27 // 请求方法
28 method: request.method,
29
30 // url
31 url: (request.url + "").replace(/\?[^?]+$/, '')
32
33 }, Mock);
34
35 response.writeHead(resultData.status, {
36
37 // 设置跨域
38 "Access-Control-Allow-Origin": "*",// 允许的域
39 "Access-Control-Allow-Headers": "*",// 允许的header类型
40 "Access-Control-Allow-Methods": "*",// 允许的请求方法
41
42 // 标记服务器名称
43 "X-Powered-By": jsonfile.name + " " + jsonfile.version,
44
45 // 响应内容类型
46 "Content-Type": "application/json;charset=utf-8"
47
48 });
49
50 response.write(require('@hai2007/tool').isString(resultData.data) ? resultData.data : JSON.stringify(resultData.data));
51
52 response.end();
53
54 })
55
56 // 启动监听
57 .listen(port);
58
59 log(jsonfile.name + ' running on port:' + port);
60
61};
\No newline at end of file