针对不同路径的请求,返回不同的数据
var fs = require("fs")
var path = require("path")
function render(path, res, type='', code=200) {
res.writeHead(code, {"Content-Type": `${type?type:'text/html'};charset=utf8`})
res.write(fs.readFileSync(path), 'utf-8')
}
const route = {
"/login": (req, res) => {
render("./static/login.html", res)
},
"/home": (req, res) => {
render("./static/home.html", res)
},
"/404": (req, res) => {
render('./static/login.html', res)
}
}
基于nodejs的express框架,路由的使用方法
var express = require('express')
var app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
res.send('hello world')
})
路由路径和请求方法一起定义了请求的端点,它可以是字符串、字符串模式或者正则表达式。
// 匹配根路径的请求
app.get('/', function (req, res) {
res.send('root');
});
// 匹配 /about 路径的请求
app.get('/about', function (req, res) {
res.send('about');
});
// 匹配 /random.text 路径的请求
app.get('/random.text', function (req, res) {
res.send('random.text');
});
// 匹配 acd 和 abcd
app.get('/ab?cd', function(req, res) {
res.send('ab?cd');
});
// 匹配 /ab/******
app.get('/ab/:id', function(req, res) {
res.send('aaaaaaa');
});
// 匹配 abcd、abbcd、abbbcd等
app.get('/ab+cd', function(req, res) {
res.send('ab+cd');
});
// 匹配 abcd、abxcd、abRABDOMcd、ab123cd等
app.get('/ab*cd', function(req, res) {
res.send('ab*cd');
});
// 匹配 /abe 和 /abcde
app.get('/ab(cd)?e', function(req, res) {
res.send('ab(cd)?e');
});
可以处理多个回调,注意next()的使用
app.get('/example/b', function (req, res, next) {
console.log('response will be sent by the next function ...');
next();
}, function (req, res) {
res.send('Hello from B!');
});
//使用函数数组处理
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
var cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])
//混合使用函数和函数数组
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
app.get('/example/d', [cb0, cb1], function (req, res, next) {
console.log('response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from D!')
})