简体   繁体   English

如何正确使用服务静态?

[英]How to properly use serve-static?

This question tightly relates to This issue here .这个问题与这里的这个问题紧密相关。

I'm building an nodeJS app.我正在构建一个 nodeJS 应用程序。 You can see the file architecture in the screenshot below.您可以在下面的屏幕截图中看到文件架构。 在此处输入图片说明

When I try running my index.JS file:当我尝试运行我的 index.JS 文件时:

const express = require('express')
const server     = new express()
const srcDir  = require('app-root-path');
const port = 3000

server.get('/', (req, res) => {
  res.sendFile(`${srcDir}/app/views/index.html`)
})


server.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`)
})

Issue: I get a blank page, where the console says that everything supplementary in my "app" folder (APART FROM HTML FILES THEMSELVES!) (components (js files), assets (css), etc) is unreachable: Failed to load resource: the server responded with a status of 404 (Not Found) .问题:我得到一个空白页面,其中控制台说我的“应用程序”文件夹中的所有补充内容(除了 HTML 文件本身!)(组件(js 文件)、资产(css)等)无法访问: Failed to load resource: the server responded with a status of 404 (Not Found) I know that the origin of the issue might be in establishing serve-static (which I don't understand), although it has always worked perfectly without it.我知道问题的根源可能在于建立静态服务(我不明白),尽管没有它它总是可以完美运行。

Can anyone help out?任何人都可以帮忙吗? Thanks in advance.提前致谢。

PS Console logs: PS控制台日志: 在此处输入图片说明

You have to tell Express where the root directory of your static files is.您必须告诉 Express 静态文件的根目录在哪里。 Usually in the wild - this directory is called public and will contain all of your css, js files, which you want to ship to the browser.通常在野外 - 这个目录被称为public并且将包含您想要发送到浏览器的所有 css、js 文件。 Do not include views or any other backend files.包括views或任何其他后端文件。

So in your case: create a new directory called public and put assets and components in there.所以在你的情况下:创建一个名为public的新目录并将assetscomponents放在那里。

Then in your Express server:然后在您的 Express 服务器中:

app.use(express.static(`${srcDir}/app/public`));

Try using the methods outlined in the express.js docs尝试使用express.js 文档中概述的方法

const staticDir = './views' // Or wherever it's being served from
server.use(express.static(staticDir)); 

You can also choose a specified path pre-fix to show these files from您还可以选择指定的路径前缀来显示这些文件

server.use('/static', express.static(staticDir))

You need to add the "components" with express.static("directory") , like it's explained here: https://expressjs.com/en/starter/static-files.html您需要使用express.static("directory")添加“组件”,就像这里解释的那样: https : //expressjs.com/en/starter/static-files.html

In your case, add this in your app.在您的情况下,将其添加到您的应用程序中。

server.use(express.static("app/components"));

To access the file FeaturePage/MainDisplay.js for example, you have to use this in your html.例如,要访问文件FeaturePage/MainDisplay.js ,您必须在 html 中使用它。

<script src="/FeaturePage/MainDisplay.js"></script>

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

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