Nodejs implement routing

  1. index.html (main page)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<a href="http://localhost:3000">进入主页面</a>
	</body>
</html>
  1. main.html (enter the main page)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<h1>这是主页面</h1>
		<a href="http://localhost:3000/test">进入test页面</a>
		<a href="http://localhost:3000/admin">进入个人页面</a>
	</body>
</html>
  1. test.html (test page)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<h1>这是测试页面</h1>
	</body>
</html>
  1. admin.html (personal page)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<h1>这是个人主页</h1>
	</body>
</html>
  1. index.js (implement routing)
//引入koa模块
const Koa=require("koa");
//引入koa里的route路由
const route=require("koa-route");
//引入fs模块
const fs=require("fs");
//创建koa对象
var app=new Koa();
//绑定中间件
var main=ctx=>{
	ctx.type="html";
	ctx.body=fs.createReadStream("./main.html");
}
var test=ctx=>{
	ctx.type="html";
	ctx.body=fs.createReadStream("./test.html");
}
var admin=ctx=>{
	ctx.type="html";
	ctx.body=fs.createReadStream("./admin.html");
}
//执行中间件(路径,中间件名)
app.use(route.get("/",main));
app.use(route.get("/test",test));
app.use(route.get("/admin",admin));
//监听
app.listen(3000);

Run in cmd: node index.js. Enter: localhost: 3000 in the browser

Note: All files are in a unified directory, if not, modify the directory

Published 19 original articles · praised 20 · visits 504

Guess you like

Origin blog.csdn.net/Handsome_gir/article/details/104917690