简体   繁体   English

nodejs express 应用程序从 public/js 文件夹中提供静态文件不起作用

[英]nodejs express app serve static files from public/js folder not work

I am developing a nodejs express project.我正在开发一个 nodejs express 项目。

In the project there is a public folder with many subfolders like js, css, images etc. Originally serving files from these folders was using this code:在项目中有一个公用文件夹,其中包含许多子文件夹,如 js、css、images 等。最初从这些文件夹中提供文件是使用以下代码:

app.use(express.static(__dirname + '/public'));

All requested files can be served by the server using this, but files in the js folder not found by the server.服务器可以使用它来提供所有请求的文件,但是服务器找不到 js 文件夹中的文件。 If I change the folde name from 'js' to somthing else then it works.如果我将文件夹名称从“js”更改为其他名称,那么它可以工作。

So for example this not found by server if the requested url is /js/work/work.js:因此,例如,如果请求的 url 是 /js/work/work.js,则服务器找不到:

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

but this is found if requested url is /asd/work/work.js:但如果请求的 url 是 /asd/work/work.js,则会发现这一点:

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

Earlier I was using Mac and Windows for development but now I switched to Ubuntu and then happed this strange thing.早些时候我使用 Mac 和 Windows 进行开发,但现在我切换到 Ubuntu,然后发生了这个奇怪的事情。

1. Add this middleware in the index.js above you set view engine 1.在你设置的视图引擎上面的index.js中添加这个中间件

  app.use(express.static(path.join(__dirname, "public")));

2. Folder Structure 2.文件夹结构

|__public/   
    |__ css/
        |__ css files...
    |__ js/
        |__ js files...

3. Import this way 3.这样导入

Now you set the path to the public directory you have to give the path public folder when you import现在您设置公共目录的路径,您必须在导入时提供路径公共文件夹

//For CSS File
<link rel="stylesheet" href="/css/main.css" />

//For JS File
<script src="/js/script.js"></script>

You should now be all set up to access CSS or any file您现在应该已准备好访问 CSS 或任何文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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