Express在嵌套目录中提供静态文件 [英] Express serve static files in nested directory

查看:75
本文介绍了Express在嵌套目录中提供静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用表达和渲染模板视图并不陌生,但是最近我尝试了一种新的目录结构,该目录结构似乎使我的应用程序实例感到困惑。

I am not new to working with express and rendering template views but recently I tried a new directory structure which seems to have confused my app instance.

它不再现在不再提供我的静态引导程序,css和图像文件,并且我的视图现在看起来一团糟。

It no longer serves my static bootstrap, css and image files anymore and my view looks all messed up now.

这是我的目录结构

AppName
 - node_modules folder
 - src (all code live here)
        - public (statics)
             - css/mycss, bootstrapcss
             - js/ myjs, bootstrapjs
             - images folder
        - models
        - app.js (entry point)

静态文件似乎比根目录深两级。在我的 app.js 文件中,我曾尝试使用 express静态方法像这样:

The static files seem to be two levels deeper than the root directory. In my app.js file, I have tried using express static method like so:

app.use( express.static(path.join(__dirname, './src' + '/public')));

,还尝试了以下操作:

app.use('/src', express.static(path.join(__dirname, '/public')));

在我看来,例如静态函数的调用方式如下:

In my views, for example the statics are called like this:

<link href="../public/css/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="../public/fonts/glyphicons-halflings-regular.ttf">
<link rel="stylesheet" href="../public/css/styles.css" type="text/css">

<script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/1.0.0-alpha.2/classic/ckeditor.js"></script>

,但仍然无法将这些文件提供给我查看。我坚持下去。
有人可以帮我吗?谢谢

but still unable to serve those files to my views. I'm stuck on this. Can someone help me out? Thanks

推荐答案

尝试一下:

app.use(express.static(path.join(__dirname, 'src/public')));

然后:

<link href="/css/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="/fonts/glyphicons-halflings-regular.ttf">
<link rel="stylesheet" href="/css/styles.css" type="text/css">

这篇关于Express在嵌套目录中提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆