【问题标题】:app.get is not workingapp.get 不工作
【发布时间】:2015-12-17 14:24:59
【问题描述】:

我的后端正在处理我包含在其中的其他文件,但这些新文件位于目录中名为 js 的文件夹中。这些是文件夹中唯一的文件,它们没有加载,我不知道为什么。我假设这只是一个语法错误,但一个小时后无法弄清楚。

在我的 html 中,我有以下代码:

<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
        <script type="text/javascript" src="js/TweenMax.min.js"></script>
        <script type="text/javascript" src="js/cooltext.animations.js"></script>
        <script type="text/javascript" src="js/cooltext.min.js"></script>

在我的 app.js 中,我使用了以下代码:

app.get('/js/jquery-1.10.2.min.js', function (req, res) {
    res.sendFile(__dirName + '/js/jquery-1.10.2.min.js');
});

app.get('/js/TweenMax.min.js', function (req, res) {
    res.sendFile(__dirName + '/js/TweenMax.min.js');
});

app.get('/js/cooltext.animations.js', function (req, res) {
    res.sendFile(__dirName + '/js/cooltext.animations.js');
});
app.get('/js/cooltext.min.js', function (req, res) {
    res.sendFile(__dirName + '/js/cooltext.min.js');
});

【问题讨论】:

    标签: javascript express server backend


    【解决方案1】:

    我想通了。我不得不使用:

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

    并从 index.html 中的链接中删除“js”。

    【讨论】:

    • 您在最初的问题中没有提到这一点 :) 很高兴知道!
    【解决方案2】:

    引用 Express 的文档:http://expressjs.com/starter/static-files.html


    在 Express 中提供静态文件

    服务文件,例如图像、CSS、JavaScript 和其他静态文件是在 Express 中内置的中间件 - express.static 的帮助下完成的。

    将要标记为静态资产位置的目录名称传递给 express.static 中间件以直接开始提供文件。例如,如果您将图像、CSS 和 JavaScript 文件保存在名为 public 的目录中,您可以这样做:

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

    现在,您将能够加载公共目录下的文件:

    http://localhost:3000/images/kitten.jpg
    http://localhost:3000/css/style.css
    http://localhost:3000/js/app.js
    http://localhost:3000/images/bg.png
    http://localhost:3000/hello.html
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      相关资源
      最近更新 更多