【问题标题】:Express.js server cannot render css and js fileExpress.js 服务器无法渲染 css 和 js 文件
【发布时间】:2021-04-28 17:39:23
【问题描述】:

我正在关注 YouTube 上关于 NODE.js 和 Express.js 的教程。我已进入 Express 部分,无法呈现网页的 CSS 和 JS 文件。 index.html 和 logo.svg 文件被呈现给服务器。任何帮助将不胜感激呈现 CSS 和 JS 文件。我的文件结构是:

Main_Folder
  |navbar-app
    |index.html
  |public
    |browser-app.js
    |styles.css
    |logo.svg
  |app.js

App.js

const express = require('express');
const app = express()
const path = require('path')

app.use(express.static('./public'))

app.get('/', (req,res) => {
    res.sendFile(path.resolve(__dirname, './navbar-app/index.html'))
})

app.all('*', (req,res) => {
    res.status(404).send('<h2>Resource not found</h2>');
})

app.listen((5000), () => {
    console.log('server')
})

【问题讨论】:

  • 要在前端打印的静态文件可以通过将express.static(path.join(__dirname, '/path')) 放在目标路径中来加载。 Check here

标签: node.js express


【解决方案1】:

您缺少导入静态文件 (app.use(express.static(__dirname)) ),必须将其放在应用调用方法之前,如下所示:

const express = require('express');
const app = express()
const path = require('path')

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

app.get('/', (req,res) => {
    res.sendFile(path.resolve(__dirname, './navbar-app/index.html'))
})
...

【讨论】:

  • 感谢您的回答,但我尝试添加代码仍然没有显示静态文件。
  • 请注意,解决方案是在 html 文件中添加“type = text/css”。这允许渲染 css 文件。
猜你喜欢
  • 2018-04-03
  • 2017-05-20
  • 2022-01-08
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 2021-04-09
  • 2021-10-30
  • 2020-07-20
相关资源
最近更新 更多