Nodejs express 可以设置 root path 吗?
Nodejs express 可以设置 root path 吗?
RT ,类似 java 中工程名那种,原地址 http://www.test.com,想变成 http://www.test.com/abc 这种,需要怎么设置或下载插件呢?谢谢
2 回复
let router = express.Router();
router.get(’/123’, funcx…);
app.use(’/abc’, router);
http://www.test.com/abc/123 就可以访问
当然可以,Node.js 的 Express 框架允许你设置应用的根路径(root path)。这通常在创建 Express 应用实例并配置中间件和路由时使用。以下是一个简单的示例,展示了如何设置根路径:
const express = require('express');
const app = express();
const PORT = 3000;
// 设置一个基本的根路径,比如 /myapp
const rootPath = '/myapp';
// 使用一个中间件来处理根路径前缀
app.use(rootPath, (req, res, next) => {
console.log(`Request received for path: ${req.originalUrl}`);
next();
});
// 定义一个路由,注意这里的路径是相对于根路径的
app.get(rootPath + '/hello', (req, res) => {
res.send('Hello from the root path!');
});
// 启动服务器
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}${rootPath}`);
});
在这个示例中,我们通过 app.use(rootPath, ...)
设置了一个中间件,它会在所有请求被处理之前检查路径前缀。然后,我们定义了一个路由 /hello
,这个路由的实际路径是 /myapp/hello
。
这样,当你访问 http://localhost:3000/myapp/hello
时,服务器会响应 “Hello from the root path!”。这种方法允许你灵活地为你的 Express 应用配置一个根路径。