闲来无事,想着作为一个前端开发也想了解下后端接口是怎么实现的,了解了下node开发对于前端也比较好上手。
白天上班,晚上花了几天打游戏的时间学习了下node基础,现在来分享node基础学习的成果啦!
以下是简单路由搭建的过程:
首先创建一个文件夹放代码,在里面创建了static文件夹(有在学习node的小伙伴们可以用node的fs模块参照文档去创建)
static文件夹下简单创建几个html页面附图:
home.html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
home页面
</body>
</html>
在项目根目录创建一个serve.js文件代码如下:
const http = require('http');
const fs = require('fs');
http
.createServer((req, res) => {
const urlObj = new URL(req.url, 'http://127.0.0.1/');
switch (urlObj.pathname) {
case '/home':
render(res, './static/home.html');
break;
case '/about':
render(res, './static/about.html');
break;
default:
res.writeHead(404, { 'Content-Type': 'text/html;charset=utf8' });
res.write(fs.readFileSync('./static/404.html'), 'utf-8');
res.end();
break;
}
})
.listen(3000, () => {
console.log('server start');
});
function render(res, path) {
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf8'
});
// 读取相应的文件返回给前端
res.write(fs.readFileSync(path), 'utf-8');
res.end();
}
此时我们控制台运行下node server.js(想改完代码服务自动重启刷新的可以去了解下nodemon或node-dev),打开浏览器访问127.0.0.1:3000/home就能看到相应的页面返回了(这边代码处理了home、about其他页面统一为404页面)
细心你们会发现,有个favicon.ico状态404,别着急,后面我会统一处理。
虽然简单的路由接口可以了,但是我们项目开发中,我们一般都会划分route模块与api 模块,为了使得项目有模块划分的感觉,我在项目根目录又创建了route.js(处理页面路由)与api.js(处理接口路由)代码分别如下:
route.js
const fs = require('fs');
const route = {
'/home': (res) => {
render(res, './static/home.html');
},
'/about': (res) => {
render(res, './static/about.html');
},
'/favicon.ico': (res) => {
render(res, './static/favicon.ico', 'image/x-icon');
},
'/404': (res) => {
res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
res.write(fs.readFileSync('./static/404.html'));
res.end();
}
};
function render(res, path, type) {
res.writeHead(200, {
'Content-Type': `${type ? type : 'text/html;charset=utf-8'}`
});
res.write(fs.readFileSync(path));
res.end();
}
module.exports = route;
api.js
const fs = require('fs');
const apiRoute = {
'/api/list': (res) => {
const list = [
{
name: '张三',
age: 23
},
{
name: '李四',
age: 25
}
];
render(res, list);
}
};
function render(res, data, type) {
res.writeHead(200, {
'Content-Type': `${type ? type : 'application/json;charset=utf-8'}`
});
res.write(JSON.stringify(data));
res.end();
}
module.exports = apiRoute;
页面路由与api路由,以对象的形式导出,这边对/favicon.ico也做好了处理。此时我们得改造下我们server.js,使得我们能在里面引入页面路由与api路由,得到相应的返回。改造好的代码如下:
server.js
const http = require('http');
const route = require('./route');
const api = require('./api');
const Router = {};
// 合并路由对象
Object.assign(Router, route, api);
http
.createServer((req, res) => {
const urlObj = new URL(req.url, 'http://127.0.0.1/');
try {
Router[urlObj.pathname](res);
} catch (error) {
Router['/404'](res);
}
})
.listen(3000, () => {
console.log('server start');
});
浏览器访问下我们会发现访问/api/list返回了我们定义好的json数据,访问/home返回了home.html里的内容,favicon.ico图标也相应的显示,状态200。心里已经是美滋滋了。
反复看了下代码,发现我们传统vue、react项目里,一般引入route和api一般在main.js,我其实是可以对我的项目进行优化,解耦下逻辑。于是最终版的方案来了。
首先我对server.js里代码进行改造,封装两个函数use()与start()代码如下:
main.js
const http = require('http');
const Router = {};
//注册路由
function use(obj) {
Object.assign(Router, obj);
}
function start() {
console.log(Router, 'Router');
http
.createServer((req, res) => {
const urlObj = new URL(req.url, 'http://127.0.0.1/');
try {
Router[urlObj.pathname](res);
} catch (error) {
Router['/404'](res);
}
})
.listen(3000, () => {
console.log('server start');
});
}
module.exports = {
start,
use
};
然后在根目录新建了个文件main.js,我想在main.js里实现页面路由与api路由的导入,并且启动node项目。
main.js
const server = require('./server');
const route = require('./route');
const api = require('./api');
server.use(route);
server.use(api);
server.start();
此时我们关闭之前运行的终端,node main.js运行下,我们会发现页面路由/home、/about正常访问,/api/list接口路由正常返回json数据,匹配不到的路由地址统一返回404.html。运行效果和我的预期一致,到此简单的node路由项目我们就搭建好了。
整体的项目结构给大家参考下:
虽然现在有很多框架帮我们封装这些东西,但是我们在开发之余也得思考项目脚手架的逻辑是怎么实现的,学着去做搭轮子的人哈哈。
分享自己阶段学习知识的运用,加上自己的思考,优化项目的过程。后续也有更加深层次的学习也会分享给大家,有问题欢迎一起学习讨论。越努力越幸运!!!