【问题标题】:Expressjs + ejs and a tags href urls not working with subdirectory routesExpressjs + ejs 和标签 href url 不适用于子目录路由
【发布时间】:2021-04-23 00:19:22
【问题描述】:

我肯定不明白这里的一些事情:)

app.js 文件的基本应用结构为:

const express = require('express');
const port = process.env.Port || 5000;
const app = express();
const path = require('path');

const mainRoute = require( path.join(__dirname, 'src/routes/mainRoute'));

app.use(function (req, res, next) {
    res.header('Cache-Control', 'public, max-age=3600');
    next();
});

app.use(express.static('public', {
  maxAge: '1d',
}));

app.set('views', path.join(__dirname, 'src/views'));
app.set('view engine', 'ejs');

app.use('/', mainRoute);

app.get('*', function(req, res){
    res.status(404).send('404???')
});

app.listen( port, () => console.log(`Listening on port`, port ));

还有一个基本结构的route.js文件为:

const express = require('express');
const mainRoute = express.Router();

mainRoute.get('/', async (req, res) => {
    res.render('page', {url: 'pageone', title: 'page 1'});    
});

mainRoute.get('/pageone', async (req, res) => {
    res.render('page', {url: 'pagetwo', title: 'page 2'});    
});

mainRoute.get('/pagetwo', async (req, res) => {
    res.render('page', {url: 'pageone', title: 'page 1'});    
});

module.exports = mainRoute;

在 page.ejs 模板上的一些简单的东西:

<a href="/<%= url %>"> 
    <%= title %> 
</a>
<hr />
 <a href="/"> 
    home 
</a>

然后添加具有相同路由和 page.ejs 的第二条路由

app.use('/loc', mainRoute);
app.use('/sub', mainRoute);

所以,现在问题在于我加载 URL 时:

http://localhost:5000/sub

然后页面上的链接呈现视图源 href="/pageone" 因此,当我单击这些链接时,页面转到 http://localhost:5000/ 并没有保持 '/sub' 设置主要路线

例如,在 angular2 中,我可以保留所有链接并尊重在索引上设置了基本 url 标签的子文件夹

但在 expressjs 上似乎不是这样

如何将页面上的所有链接保留到 /sub 或 /loc 路径?不渲染或添加到 ejs 模板?

我的意思是,有相对于路由目录的链接?

【问题讨论】:

    标签: express ejs


    【解决方案1】:

    您可以使用req.baseUrl 获取路由器安装的路径。您可以将其传递给 page.ejs 视图并构建 URL。

    // mainRoute.js
    
    mainRoute.get('/', async (req, res) => {
      res.render('page', { url: 'pageone', title: 'page 1', baseUrl: req.baseUrl })
    })
    
    mainRoute.get('/pageone', async (req, res) => {
      res.render('page', { url: 'pagetwo', title: 'page 2', baseUrl: req.baseUrl })
    })
    
    mainRoute.get('/pagetwo', async (req, res) => {
      res.render('page', { url: 'pageone', title: 'page 1', baseUrl: req.baseUrl })
    })
    
    <!-- page.ejs -->
    
    <a href="<%= `${baseUrl}/${url}` %>">
      <%= title %> 
    </a>
    <hr />
    <a href="<%= baseUrl %>"> 
      Home
    </a>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2017-01-06
    相关资源
    最近更新 更多