在 express 中提供静态文件在不同的路由中不起作用,仅在根路由中起作用

Serve static files in express doesn't work in different routes, only in root route

我已经对这个问题做了一些研究,但所有可能的解决方案都不适合我,我不知道为什么。

我正在使用 page.js 和 express 来开发我的小应用程序。当我提供我的静态文件时,在我的“/”(根)路径中一切正常。但是当我导航到其他路线时,例如“/client-profile/:user_id”,我的静态文件似乎没有服务,因为我的模板只显示断开的链接,有时不显示我什么都可以。

当我在浏览器中使用 "inspect element" 工具处理“/”路线中的一张图片时,它会显示例如“/image.jpg”,但是当我转到其他路线时(“ /client-profile/:user_id") 与相同的图像,它显示我 "/client-profile/image.jpg"

这是我的代码:

server.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') 时,您应该将所有静态资源放在 public 文件夹中,并将相对路径放在 html 页面中,如下所示: 对于 public 目录中的 index.js 文件,写入

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