简体   繁体   English

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

[英]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. 我正在使用page.js和express来开发我的小应用程序。 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. 但是当我导航到其他路线时,例如“/ client-profile /:user_id”,看起来我的静态文件似乎没有服务,因为我的模板只显示断开的链接,有时候没有显示任何内容。

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" 当我在浏览器中使用“检查元素”工具而不是“/”路径中的一个图像时,它会向我显示例如“/image.jpg”,但是当我转到其他路径时(“/ client-profile /:user_id”) )使用相同的图像,它显示“/client-profile/image.jpg”

Here is my code: 这是我的代码:

server.js (express) 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) 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) (注意:我的所有静态文件,无matter是什么类型,都在项目根文件夹中名为“public”的文件夹中)

In advance, thanks a lot! 提前,非常感谢!

当你使用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