【问题标题】:How to add static file from `node_modules` after declare the `public` as static in express?将`public`声明为express中的静态文件后,如何从`node_modules`添加静态文件?
【发布时间】:2017-06-18 00:50:33
【问题描述】:

在我的express 应用程序中,我保留了以下配置:

var express = require("express");
var path = require("path");
var jsonServer = require("json-server");
var app = express( );

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

app.get("/", function( req, res ) {
    res.sendFile( express.static(  path.join(__dirname, "/public/index.html" ) ) );
});

app.use('/api', jsonServer.router('./db.json'));

app.listen( 3000 );

这一切都很好。问题是,我无法从node_modules 添加jquery。这是我的 HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Promise Defined</title>
    <script src="node_modules/jquery/dist/jquery.js" type="text/javascript"></script> //not working sibling folder of public
    <link rel="stylesheet" href="styles/app.css"> //works fine. inside public folder
</head>
<body>
    <h1>New Title</h1>
</body>
</html>

解决此问题的正确方法是什么?或者如何处理这种情况? 提前致谢。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    node.js 默认不提供任何文件(与其他一些 Web 服务器不同)。因此,如果您希望node_modules/jquery/dist/jquery.js 工作,那么您必须确保您的express.static() 代码行将包含该文件,或者您必须专门为该文件定义一个路由。此外,有时使用没有前导 / 的相对路径是危险的,因为这使得它相对于您的页面路径,这通常是不必要的,并且如果您想在许多不同的文件中提供相同的文件,这可能会使事情变得困难您网站上的页面。

    例如,您可以在网页中执行此操作:

    <script src="/jquery.js" type="text/javascript"></script>
    

    还有,这个:

    app.get("/jquery.js", function(req, res) {
        res.sendFile(path.join(__dirname, "node_modules/jquery/dist/jquery.js"));
    });
    

    就我个人而言,我可能会将 jquery.js 移动到我服务器上的 public/scripts 目录中,因此我不会从 node_modules 目录中提供任何内容,因此我所有公开提供的文件都集中在一个地方,因此完全清楚什么可以提供给客户而不能提供给客户,因此我可以设计一两个 express.static() 语句来提供我所有的公共文件。

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 2011-04-25
      相关资源
      最近更新 更多