简体   繁体   中英

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

I have make some research about this issue, but all the possible solutions doesn't work for me I don' know why.

I am using page.js and express to develop my little app. When I serve my static files all works fine in my "/" (root) route. But when I navigate to other route, for example "/client-profile/:user_id", it seem like my static files doesn't serve, because my template show me only breaked links, and sometimes doesn't show me anything.

When I use "inspect element" tool in my browser over one image in the "/" route, it shows me for example "/image.jpg", but when I go to other route ("/client-profile/:user_id") with the same image, it shows me "/client-profile/image.jpg"

Here is my code:

server.js (express)

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()
    })
}

(Note: all my static files, no mattter what type, are in a folder named "public" in the root folder of the project)

In advance, thanks a lot!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM