Nodejs_7
1、express框架介绍
之前那个http模块比较麻烦,所以一般会使用一些框架
Express基于 Node.js 平台,快速、开放、极简的 Web 开发框架Express中文网
2、express 初体验
-
下载包并导入模块
npm i expressconst express = require('express'); -
创建一个应用对象
const app = express(); -
创建路由
app.get('/home', (req, res) => { // 请求方法为 GET // 路径为 /home,之前不是要if if 嘛 // 如果输入 http://127.0.0.1:8080/ // 404 Not Found res.end('haha'); // req, res 和 http 模块是类似的 }) -
监听端口
app.listen(8080,() => { console.log('listening on 8080'); });
3、路由
路由是指应用程序的端点 (URI) 如何响应客户端请求,就是根据请求来选择是谁处理
1.使用
路由 由三部分组成:请求方法、路径 和 回调函数
app.方法名(路径,回调函数)
// 上面的初体验就是
app.get('/home', (req, res) => {}
app.get('/', (req, res) => {
// 输入 http://127.0.0.1:8080/就没事了
res.end('/haha');
})
app.all('*', (req, res) => {
// 啥都行,一般进行 404 响应
res.end('<h1>404 Not Found</h1>');
})
<form method="post" action="http://127.0.0.1:8080/login">
<button>login</button>
</form>
app.post('/login', (req, res) => {
res.end('login...');
})
2.获取请求参数
// 原生
console.log(req.method);
console.log(req.url);
console.log(req.httpVersion);
console.log(req.headers);
// express 操作
console.log(req.path); // 路径
console.log(req.query); // 查询字符串
console.log(req.ip); // ip
console.log(req.get('host')); // 获取某一个请求头
3.获取路由参数
req.params 和 占位符 :名
app.get('/:id', (req, res) => {
// req.params 是所有的路由参数,后面.id 要和上面一致
console.log(req.params.id);
// http://127.0.0.1:8080/xixi -----> xixi
res.end('haha');
})
小练习:
根据歌手的id显示对应的页面
const singer = [
{
name: '小明',
id: 1000
},
{
name: '小红',
id: 1001
},
{
name: '大锦鲤',
id: 1002
}
]
app.get('/singer/:id.html', (req, res) => {
res.setHeader('content-type', 'text/html; charset=utf-8');
// req.params 是所有的路由参数,后面.id 要和上面一致
let id = req.params.id;
// 使用 find 方法, 也可以使用forEach
let haha = singer.find(i => {
// 获取的id 是字符串,需要转换成 number
if (i.id === Number(id)) return true;
})
if (haha !== undefined) {
console.log(haha);
res.end(haha.name);
return ;
}
res.end('<h1>404 Not Found</h1>');
})
4.设置响应
// res.status(500); // 状态码
// res.set('aaa', 'bbb'); // 响应头
// // aaa: bbb
// // 自动添加 Content-Type: text/html; charset=utf-8
// res.send('Hello World!'); // 响应体
// 链式调用 set 要放在 send 前
res.status(200).set('ad','fd').send('haha');
4.1其他响应
跳转
res.redirect('https://baidu.com'); // 这里少一个 www
// 302 Moved Temporarily
// 多出一个响应头:重定向
// Location: https://www.baidu.com/
下载响应,后面不能有 end
res.download(__dirname + '/index.html');
json 响应
res.json({ // Content-Type: application/json; charset=utf-8
haha: 'haha',
xixi: 'wuwu',
})
响应文件
res.sendFile(__dirname + '/index.html');

被折叠的 条评论
为什么被折叠?



