在 Node.js 的http模块中,可以通过以下方式获取请求的pathname(路径名部分,不包含查询字符串等)。
const http = require('http');
const server = http.createServer((req, res) => {m
const url = new URL(req.url, `http://${req.headers.host}`);
const pathname = url.pathname;
console.log(`Received request for pathname: ${pathname}`);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at port ${port}`);
});
这里使用了URL对象来解析请求的 URL,从而可以准确地获取到pathname。这样做的好处是可以方便地处理不同的 URL 部分,包括路径名、查询参数、锚点等。
在 Express 框架中,可以很容易地获取请求的路径(path)和路径名(pathname)。
获取路径(包括查询字符串等):
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const path = req.path;
console.log(`Received request for path: ${path}`);
res.send('Hello World!');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running at port ${port}`);
});
获取路径名(不包含查询字符串等):
可以结合内置的url模块来获取更精确的路径名。
const express = require('express');
const url = require('url');
const app = express();
app.get('/', (req, res) => {
const parsedUrl = url.parse(req.url);
const pathname = parsedUrl.pathname;
console.log(`Received request for pathname: ${pathname}`);
res.send('Hello World!');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running at port ${port}`);
});
或者直接使用 Express 的内置方法获取路径的各个部分:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const { path, pathname } = req._parsedUrl;
console.log(`Received request for path: ${path}`);
console.log(`Received request for pathname: ${pathname}`);
res.send('Hello World!');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running at port ${port}`);
});