【问题标题】:I am not able to access my css and js file in public to my index.hbs in views folder我无法在views文件夹中公开访问我的css和js文件到我的index.hbs
【发布时间】:2021-12-03 20:21:11
【问题描述】:

我正在尝试从视图文件夹中的 index.hbs 访问公共文件夹中的 css 和 js 文件。

index.js 文件:

        const express = require('express')
        const path = require('path')
        // const hbs = require('hbs')
        const app = express()
        const port = 3000

        // const stat = path.join(__dirname, '../public')

        // app.use(express.static(stat))
        app.set('view engine' ,'hbs');
        app.set('/' ,path.join(__dirname, '/views'));


         app.get('/', (req, res) => {
          res.render('index', {})
          })
          app.get('/', (req, res) => {
          res.send("Hello")
          })

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

index.hsb中css和JS的链接:

<link rel="stylesheet" href="css/style.css">
<script src="javascript/main.js"></script>

文件夹结构

【问题讨论】:

标签: node.js express view backend hsb


【解决方案1】:

1。在index.js上面添加这个中间件你设置的视图引擎

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

2。文件夹结构

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

3.以这种方式导入

现在您设置公共目录的路径,您必须在导入时提供路径公共文件夹

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

您现在应该可以访问 css 或任何文件了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2018-06-21
    • 2013-04-07
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    相关资源
    最近更新 更多