在 Express 中提供静态文件在不同的路由中不起作用,只能在根路由中工作



我对这个问题进行了一些研究,但我不知道为什么,所有可能的解决方案都对我不起作用。

我正在使用页面.js和快递来开发我的小应用程序。当我提供静态文件时,在我的"/"(根)路由中一切正常。但是当我导航到其他路由时,例如"/client-profile/:user_id",似乎我的静态文件不起作用,因为我的模板只显示断开的链接,有时不显示任何内容。

当我在浏览器中对"/"路由中的一个图像使用"检查元素"工具时,它会显示例如"/image.jpg",但是当我使用相同的图像转到其他路由("/client-profile/:user_id")时,它会显示"/client-profile/image.jpg">

这是我的代码:

服务器.js(快速)

var express = require('express')
var path = require('path')
lisaPosApp.use(express.static(path.join(__dirname, '/public')))
lisaPosApp.get('/client-profile/:user_id', function (req, res) {
res.render('index', { title : '.: LISA | Usuarios | Loyalty Improvement Service Application :.' })
})

index.js (pagejs)

var page = require('page')
var templateClientProfile = require('./template')
var request = require('superagent')
var header = require('../header-n-left-menu')
var utils = require('../utils')
page('/client-profile/:user_id', utils.loadUserAuth, header, loadClientInfo, function (ctx, next) {
$('title').html(`.: LISA | ${ctx.user.username} | Loyalty Improvement Service Application :.`)
var mainContainer = document.getElementById('main-container')
mainContainer.innerHTML = ''
mainContainer.appendChild(templateClientProfile(ctx.user))
document.getElementById('section-preloader').remove()
$('select').material_select()
$('ul.tabs').tabs()
})
function loadClientInfo (ctx, next) {
request
.get(`/api/client-profile/${ctx.params.user_id}`)
.end(function (err, res) {
if (err) return console.log(err)
ctx.user = res.body
next()
})
}

(注意:我所有的静态文件,不管是什么类型,都在项目根文件夹中名为"public"的文件夹中)

提前,非常感谢!

当你使用express.static('/public')时,你应该把所有的静态资源放在公用文件夹中,并在你的html页面中放置相对路径,如下所示: 对于公共目录中的索引.js文件,写入

<script src="/index.js"></script>

最新更新