1.路由
路由是指客户端请求地址与服务器端程序代码的对应关系。简单的说,就是请求什么响应什么。
- 客户端发来请求
- 获取请求路径(包含请求参数):req.url
- 获取不携带参数的请求地址:parse方法(弃用?)
- 同一个请求地址是否有不同的请求方式?
const http = require('http');// 1.引入系统模块http
const url = require('url');
const app = http.createServer();// 2.创建网站服务器
app.on('request', (req, res) => {// 3.为网站服务器对象添加请求事件
// 4.实现路由功能
// 4.1 获取请求方式 并转换成小写
const method = req.method.toLowerCase();
// 4.2 获取请求地址
const pathname = url.parse(req.url).pathname;
res.writeHead(200, {
'content-type': 'text/html;charset=utf8' //因为响应体里有中文
});
if (method == 'get') {
if (pathname == '/' || pathname == '/index') {
res.end('欢迎来到首页')
}else if (pathname == '/list') {
res.end('欢迎来到列表页')
}else {
res.end('您访问的页面不存在')
}
}else if (method == 'post') {
}
});
app.listen(3000);
console.log('服务器启动成功')
2. 静态资源
服务器端不需要处理,可以直接响应给客户端的资源就是静态资源,例如CSS、JavaScript、image文件。
访问:
3. 动态资源
相同的请求地址,传递不同的请求参数,得到不同的响应资源,这种资源就是动态资源。
http://www.itcast.cn/article?id=1
http://www.itcast.cn/article?id=2