【问题标题】:nodejs serving static files (path issue) (unable to go down dir "/../")nodejs 提供静态文件(路径问题)(无法进入目录“/../”)
【发布时间】:2018-08-09 22:11:47
【问题描述】:

问题的简要概述

我在routes.js 文件中,如何将css 文件夹中的所有文件作为静态文件提供?

path structure (someone edit this and make the img visible without use of link)


一些失败的尝试

path.join(__dirname, '\\css') -> 输出 -> \\app\\routes\\css

path.join(__dirname, '..\\css') -> 输出 -> \\app\\routes\\css

path.join(__dirname, '..', 'css') -> 输出 -> \\app\\routes\\css


想要的路径是:\\app\\routes\\..\\css

但由于某种原因,“/../”被忽略了。 routes.js中的cmets


routes.js

var express = require("express");

var path = require('path');


var appRouter = function (app) {

  app.use(express.static(path.join(__dirname, '\\css')));
   // RESULTS IN INVALID PATH: '\\app\\routes\\css'

   // (there is no css folder inside the routes folder) 

  app.get('/', function (req, res) {
    res.redirect('/home');
      });
};

module.exports = appRouter;

server.js

var express = require("express");
var bodyParser = require("body-parser");
var routes = require("./routes/routes.js");
var app = express();

const server_port = process.env.PORT || 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

routes(app);

var server = app.listen(server_port);

Index.html

        // I have linked to the static css file
<link rel="stylesheet" type="text/css" href="css/styles.css" />

其他信息

app.use(express.static('app')); 有效,但是它为整个 app 文件夹中的所有文件提供服务,这是不可取的。

【问题讨论】:

    标签: node.js express path


    【解决方案1】:

    使用

    path.join(__dirname, '/../css')

    (需要在目录名前加上/

    【讨论】:

    • 你解决了,只需要从index.html的href中删除“css/”部分,一切都按预期工作。