使用node和express来服务get(/foo/:bar)请求,当res.render(template)时,template中的所有相对链接都是相对于/foo而不是/

cgh8pdjw  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(149)

我的节点服务器代码中的违规路由是这样的:

app.get('/s/:searchTerm', function(req, res) {
  res.render('index');
});

发生这种情况后,index.jade中的所有相对链接都是相对于“hostname/s/”而不是“hostname/"的,这是断开的。
我的节点设置看起来像这样:

app.set('view engine', 'jade');
app.set('views', __dirname + '/views');

app.use(express.static(__dirname + '/public/'));
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));

app.use(express.json());
app.use(app.router);

除了/s/:searchTerm路由之外,所有这些路由都可以工作。即使是/results路线也有效。在那里,partials/result中的相对链接是相对于'hostname'的,正如我所期望的那样。

app.get('/', function(req, res) {
  res.render('index');
});

app.get('/s/:searchTerm', function(req, res) {
  res.render('index');
});

app.get('/results', function(req, res) {
  res.render('partials/results');
});

index.jade简单地引用布局.jade:

extends layout

layout.jade的开头是这样的:

!!! 5
html(lang='en' data-ng-app='FooApp')
  head
    meta(charset='utf-8')
    meta(http-equiv='X-UA-Compatible', content='IE=edge')
    meta(name='viewport', content='width=device-width, initial-scale=1.0')
    meta(name='author', content='foo@gmail.com`')
    link(rel='shortcut icon', href='img/favicon.ico')
    title FooApp.com â„¢
    // Bootstrap core CSS 
    link(href='//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css', rel='stylesheet')
    // Custom css for this template 
    link(href='css/style.css', rel='stylesheet')
    //if lt IE 9
      script(src='https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js')
      script(src='https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js')
  body(data-ng-controller='SearchController'
    .navbar.navbar-inverse.navbar-fixed-top(role='navigation')
    .container
      .navbar-header
        button.navbar-toggle(type='button' data-target='.navbar-collapse'

我如何呈现一个部分并保持该部分中相对于“主机名”的链接?
编辑:增加了索引.玉和布局.玉码
编辑:啊,我看到我在做一些多余的favicon。

fae0ux8s

fae0ux8s1#

您看到的行为是预期的,因为href是相对于加载它们的页面的。由于/a/:searchTerm路由嵌套在/a上,因此img/favicon.ico等静态资产的href将获取其相对父路由。如果你想让href在public目录的根目录中查找静态资产,那么在href前添加一个/,如下所示:/img/favicon.ico

相关问题