簡體   English   中英

在express中提供靜態文件不能在不同的路由中工作,只能在根路由中使用

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

我已經對這個問題做了一些研究,但所有可能的解決方案對我都不起作用我不知道為什么。

我正在使用page.js和express來開發我的小應用程序。 當我提供我的靜態文件時,我的“/”(根)路由一切正常。 但是當我導航到其他路線時,例如“/ client-profile /:user_id”,看起來我的靜態文件似乎沒有服務,因為我的模板只顯示斷開的鏈接,有時候沒有顯示任何內容。

當我在瀏覽器中使用“檢查元素”工具而不是“/”路徑中的一個圖像時,它會向我顯示例如“/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()
    })
}

(注意:我的所有靜態文件,無matter是什么類型,都在項目根文件夾中名為“public”的文件夾中)

提前,非常感謝!

當你使用express.static('/public')你應該將所有靜態資源放在公共文件夾中,並將相對路徑放在你的html頁面中,如下所示:對於在公共目錄中的index.js文件,寫

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

暫無
暫無

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

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