零基础之Node.js搭建API服务器的详解

2020-06-17 05:51:29易采站长站整理

exports.account = require('./account');


// index.js
const http = require('http');
const nUrl = require('url');
const config = require('./config');
const controller = require('./controller');
const route = require('./route').map(item => {
console.log(`route ${item.method}:${item.path}`);
let tuple = item.impl.split('.');
item.impl = controller[tuple[0]][tuple[1]];
return item;
});
const server = http.createServer((req, res) => {
let method = req.method;
let url = nUrl.parse(req.url);
let matchRoute = route.find(item => {
return item.method === method && item.path === url.pathname;
});
if (matchRoute) {
matchRoute.impl(req, res);
return;
}
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not Found');
});
server.listen(config.port, config.hostname, () => {
console.log(`Server running at http://${config.hostname}:${config.port}/`);
});

依旧是用node index.js启动Server,如果要在现有模式下开发一个API,主要就两步:

在route.js中定义路由
在controller/中实现

做这个程度的优化,只是为了向大家传达一些比较宽泛的概念,还不是真正用来写API服务,只是为了大伙练练手。

这个程度还达不到真实场景需求,还需要经过几轮改造,包括模块、层、common、lib、query解析,body解析、更灵活的route等一系列事情,限于篇幅,有机会在一一讲述。

经过我的描述以及代码示例,如果大家有兴趣学习Node.js,建议多搜搜相关知识,保持关注,然后在逐步去熟悉Node.js流行的Web框架如:Express、Koa等,不过框架只是更高层面的封装,基础的概念以及知识还是需要花时间才能掌握。

如果前端想尝试后端编程,请一定先学习HTTP协议,推荐《HTTP权威指南》从头到尾认真看一遍。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对软件开发网的支持。如果你想了解更多相关内容请查看下面相关链接