记给自己的 Express 的 Get 请求
上一篇文章是 Express 的 Hello World。这里我们来看看如何在 Express 中处理 Get 请求。
一般操作
一般操作,从上次没有说到的request
对象入手(下面的内容删除了关于cookie
的部门,希望我有机会能专门学习cookie
吧)。
app.get('/index', function (req, res) {
console.log(JSON.stringify(req.app === app, null, 2)); // true
console.log(`req.baseUrl: ${req.baseUrl}`); // 空,与路由有关
console.log(`req.hostname: ${req.hostname}`);
// 192.168.1.5 | localhost
console.log(`req.ip: ${req.ip}`);
// ::ffff:192.168.1.5 | ::1
console.log(`req.ips: ${req.ips}`); // 空
console.log(`req.method: ${req.method}`); // GET
console.log(`req.originalUrl: ${req.originalUrl}`); // /index
console.log(`req.params: ${JSON.stringify(req.params || [], null, 2)}`);
console.log(`req.path: ${req.path}`); // /index
console.log(`req.protocol: ${req.protocol}`); // http
console.log(`req.query: ${JSON.stringify(req.query || [], null, 2)}`);
// { "username": "tom", "password": "jerry" }
console.log(`req.route: ${JSON.stringify(req.route || [], null, 2)}`);
console.log(`req.secure: ${req.secure}`); // false
console.log(`req.subdomains: ${req.subdomains}`);
console.log(`req.xhr: ${req.xhr}`); // false
res.end();
});
首先想介绍一下关于ip
和hostname
内容,因为我第一次看到也有点蒙😮
监听host | ip | hostname |
---|---|---|
默认 | ::1 | localhost |
127.0.0.1 | 127.0.0.1 | localhost |
192.168.1.5(连接 WiFi 时本机IP) | ::ffff:192.168.1.5 | 192.168.1.5 |
参考了 资料 和 Node官网 的描述才,才知道下面的内容。
IPv6
由两部分组成:子网前缀
和接口后缀
。IPv6
一共128bit
,这两部分各64bit
。如果IPv4
地址嵌在IPv6
中,为了让任何IPv6
解析器都能知道自己正在处理一个IPv4
的地址,所以在前面加上子网前缀
。子网前缀
中的连续的 0 是可以省略的,所以::ffff:
实际上是0000:0000:ffff:0000
。
那::1
同理,是IPv6
的localhost
的简写版本,完整版应该是0:0:0:0:0:0:0:1
。
获取 Get 请求参数
使用request.query
获取URL
参数
app.get('/getUser', (req, res) => {
res.send(JSON.stringify(req.query));
});
如果要获取这些变量,可以使用解构赋值
语法,或者直接.
拿到变量
app.get('/getUser', (req, res) => {
let { name } = req.query; // tom
let age = req.query.age; // 12
let address = req.query.address; // undefined
console.log(name, age, address);
res.send(req.query);
});
其实,我以前都很好奇,如果要在参数传对象或者数组是不是只能用POST
请求,直到我看了express
的文档——用GET
一样没问题!不过都需要使用[]
运算符
先是数组,只需要使用数组名[]=参数值
// http://localhost:3000/getUser?users[]=tom&users[]=jerry&users[]=dog
app.get('/getList', (req, res) => {
let users = req.query.users
res.end(users);
});
然后是对象,需要对象名[属性名]=属性值
// http://localhost:3000/getUser?tom[name]=tom&tom[age]=12&tom[address]=house
app.get('/tom', (req, res) => {
let tom = req.query.tom;
res.end(tom);
});
获取 Get 路径参数
熟悉Springboot
的小伙伴都知道我们可以在路由中定义参数,然后使用@PathVariable
注解拿到参数,在express
中也没问题。我们需要使用:参数名
定义参数
app.get('/user/:id', (req, res) => {
console.log(req.params.id);
res.end(req.params.id);
});
当然,我们可以定义不止一个参数
app.get('/image/:width/:height', (req, res) => {
console.log(req.params.width);
console.log(req.params.height);
res.end(JSON.stringify(req.params));
});
就先分享到这里吧~