面试题答案
一键面试- 获取参数值的描述:
- 在Node.js的
http
模块中,请求的URL参数包含在url
模块解析后的query
部分。首先需要引入url
模块,然后使用url.parse
方法(在Node.js较新版本中可以使用new URL(req.url, 'http://example.com')
,这里以url.parse
为例)对请求的URL进行解析,从解析结果中获取query
部分,再使用querystring
模块(在较新版本中可以使用URLSearchParams
)对query
字符串进行解析,从而得到name
和age
参数的值。
- 在Node.js的
- 代码示例:
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const queryParams = parsedUrl.query;
const name = queryParams.name;
const age = queryParams.age;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(`Name: ${name}, Age: ${age}`);
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
在上述代码中:
- 引入了
http
、url
和querystring
模块。 - 使用
url.parse(req.url, true)
解析URL,true
参数表示将query
部分解析为一个对象。 - 从解析后的
query
对象中获取name
和age
参数的值。 - 最后在响应中返回获取到的参数值。