【问题标题】:Node.js -- Can't access static files while inside of route folderNode.js - 在路由文件夹内无法访问静态文件
【发布时间】:2018-05-27 17:45:21
【问题描述】:

我的静态文件在 app.js 中的任何路由上都能完美运行。但是我的 /routes/blog.js 文件中的任何路由都没有加载我的静态文件。

  Folder structure:

  Project
  ├── app.js 
  │ 
  │ 
  ├── public 
      └──  bootstrap...  
      └──  img...
  │
  │  
  ├──views
      └── index.html
      └── 404.html
      └── etc..
  │ 
  │ 
  ├──routes
       └── blog.js

这是我的 app.js 文件

  const express = require('express');
  const app = express(); 
  const path = require('path'); 
  const blog = require('./routes/blog') 
  //Couple other requires...


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


  // Various get routes...



  // Start our server on port 3000
  app.listen(3000, () => console.log('Node app listening on port 3000...'));

这是我的 /routes/blog.js 文件

  const express = require('express'); 
  const router = express.Router(); 


  router.get('/', (req, res) => {
    res.render('blog.html');
  });


  // Post a blog post
  router.route('/post')
    .get( (req, res) => {
    res.render('post.html');
    })

    .post( (req, res, next) => {
       //STUFF
    res.redirect('/blog');
    });

  module.exports = router;  

当我在通过 app.js 文件的任何页面上查看页面源时,我指向 htttp://localhost:3000/bootstrap/bootstrap.min.css/ 但是当我查看通过 app.js 文件的任何页面的源时blog.js 文件(例如,如果我转到 localhost:3000/blog/post)我指向 htttp://localhost:3000/blog/bootstrap/bootstrap.min.css/ 并且不会加载静态文件

【问题讨论】:

    标签: node.js express static-files


    【解决方案1】:

    添加到您的 routes.js

    const DIR = path.join(__dirname, 'routes');
    

    并将get 更改为:

    router.get('/', (req, res) => {
      res.render(path.join(DIR, 'blog.html'));
    });
    

    【讨论】:

      【解决方案2】:

      我通过改变让它工作

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

      只是

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-08
        • 1970-01-01
        • 2021-04-05
        • 1970-01-01
        相关资源
        最近更新 更多