nodejs简易服务器

简单需求使用nodejs直接创建一个简易服务器

创建node服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const http = require('http')
const fs = require('fs')
const querystring = require('querystring')
const server = http.createServer()
const router = require('./router')

const Route = new router({
"/signTransaction": { method:'post' },
"/getAllsign": { method:'get' },
})

server.on('request',function(req,res){
try {
var param = ''
req.on('data', function (chunk) {
param += chunk;
});
req.on('end', function () {
param = querystring.parse(param);
var request = {
url: req.url,
method: req.method,
param: param
}
// 交由router处理响应
Route.judgeUrl(request, res);
});
} catch (error) {
console.log(error)
}
})

process.on('uncaughtException', function (err) {
//打印出错误
console.log(err);
//打印出错误的调用栈方便调试
console.log(err.stack);
});

server.listen(8888, function(){
console.log('running on port 8888....')
})

因为post请求的参数是放在请求体里面,所以需要对请求进行监听并收集chunk数据,直到请求结束再重新解析处理

路由文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const fs = require('fs')
const path = require('path')
const transaction = require('./Transaction') // 获取转换数据接口

class router{
constructor(urls){
this.urlMap = this.urls;
this.urls = Object.keys(this.urls);
}

judgeUrl(req, res){
const routers = Object.keys(this.urls);
if(this.routers.indexOf(req.url) < 0){
res.writeHead(200, {'Content-Type':'text/plain; charset=utf-8'})
.end('Api URL is not correct,please check again ')
return
} else if(this.urlMap[req.url].method !== req.method){
res.writeHead(401, {'Content-Type':'text/plain; charset=utf-8'})
.end(`Request type error, please use ${this.urlMap[req.url].method} instead `)
return
} else {
switch(req.url){
case '/signTransaction':
this.signTransaction(req, res);
break;
case '/getAllsign':
this.signTransaction(req, res);
break;
}
}
}

signTransaction(req, res){
res.writeHead(200,{'Content-Type':'application/json; charset=utf-8'})
var trans = JSON.parse(req.param.trans)
try {
var transHash = transaction(req.param.key)(trans)
} catch (error) {
res.end(JSON.stringify(error))
return
}
res.end(JSON.stringify(transHash))
}

async getAllsign(req, res){
res.writeHead(200,{'Content-Type':'application/json; charset=utf-8'})
try {
var data = await fetchAllsign();
} catch (error) {
res.end(JSON.stringify(error))
return
}
res.end(JSON.stringify(data))
}
}
module.exports = router