1 Star 2 Fork 1

自然框架 / nf-plat-node-mysql

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
server.js 2.08 KB
一键复制 编辑 原始数据 按行查看 历史
% 提交于 2021-07-29 21:41 . 调整配置
// 引入服务
const http = require('http')
// 获取上传的body
const getBody = (req) => {
return new Promise((resolve, reject) => {
let body = ''
req.on('data', chunk => {
body += chunk
})
req.on('end', () => {
// 输出body,转换成对象
try {
if (body === '') {
resolve({})
} else {
const obj = JSON.parse(body)
resolve(obj)
}
} catch {
reject({
msg: 'json格式不正确!',
body
})
}
})
})
}
http.createServer((req, res) => {
// 设置响应头
res.writeHeader(200, {
"Content-Type" : "application/json"
})
// 输出开头
// res.write('{"code":"200" ')
// 解构获取 URL、请求方法和头部对象
const { url, method, headers } = req
console.log('\n有访问者', url, method)
// 请求体
getBody(req).then(body => {
// 需要转换成对象。
console.log('\n获取body', body)
const userInfo = {
userId: 1,
name: 'jyk',
roles: []
} // 先占个坑
// 判断url,加载对应的服务
const arr = url.split('/')
if (arr.length >= 4) {
// 符合 /api/moduleId/actionId/dataid 的形式
const moduleId = arr[2]
const actionId = arr[3]
const dataId = arr.length > 3 ? arr[4]: ''
console.log('\n获取参数:', arr)
switch (arr[1]) {
case 'api': // 加载服务
const servers = require('./src/services/index.js')
servers(userInfo, moduleId, actionId, dataId, body).then((data) => {
const re = {
code: 200
}
Object.assign(re, data)
res.write(JSON.stringify(re, null, 2))
res.end()
})
break
}
}
}).catch(err => {
console.log('访问出错:')
console.log(err)
const re = {
code: 600 // 出错了用啥编号
}
res.write(JSON.stringify(re, null, 2))
res.end()
})
})
// 设置监听端口为 6000
.listen(6000, () => {
console.log('服务已经开启:http://localhost:6000')
})
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
NodeJS
1
https://gitee.com/naturefw/nf-plat-node-mysql.git
git@gitee.com:naturefw/nf-plat-node-mysql.git
naturefw
nf-plat-node-mysql
nf-plat-node-mysql
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891