簡體   English   中英

node js express - 如何為變量url提供靜態內容

[英]node js express - how to serve a static content for variable urls

app.use文檔顯示了為靜態路由提供靜態目錄的示例,例如

app.use('/static', express.static(__dirname + '/public'));

指定應為非靜態路由提供靜態目錄的語法是什么?

通過其他地方的語法(app.get等),它看起來像app.use('/:foo', express.static(__dirname + '/public')); 應該管用。 但是,我總是得到一個Cannot GET /bar錯誤。

拉爾夫,我認為你所尋找的是“觀點”。 如果您希望您的網站路由“非靜態”,請保留app.use(express.static(__dirname + '/public'))

並設置如下視圖:

app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/public/views');

當然,你需要處理用戶試圖獲得的路線。 您需要探索: http//expressjs.com/guide.html

我使用Couchdb我會告訴你它可能會有所幫助的例子。

app.get('/:foo', function(req, res){
if (!err){
res.render('htmlname', {
title: 'somedata'
});
}}

希望它有所幫助,古德勒克

您可以使用res.sendfile()將變量路徑指向相同的靜態內容:

app.get('/:location', function(req, res){
  res.sendfile(__dirname + '/public/index.html');
});

在有了同樣的問題之后,我想出了以下解決方案:

app.use('/path/:file', function (req, res, next) {
  return express.static(require('path').join('.', 'path', req.params.file)).apply(this, arguments);
});

如果你想保留express.static附帶的所有功能,那么你可以簡單地修補req.url (因為它只是中間件):

const path = require('path');
const express = require('express');
const app = express();

// Dynamic path, but only match asset at specific segment.
app.use('/static/:foo/:bar/:asset', (req, res, next) => {
  req.url = req.params.asset;
  express.static(__dirname + '/static')(req, res, next);
});         

// Just the asset.
app.use('/static/*', (req, res, next) => {
  req.url = path.basename(req.originalUrl);
  express.static(__dirname + '/static')(req, res, next);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM