How to add static file from `node_modules` after declare the `public` as static in express?

不羁的心 提交于 2021-01-29 08:27:13

问题


In my express app, I am keeping the below config:

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 );

All this is works fine. the problem is, I am not able to add the jquery from node_modules. here is my 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>

What is the correct way to fix this? or how to handle this kind of scenario? Thanks in advance.


回答1:


node.js does not serve any files by default (unlike some other web servers). So, if you want node_modules/jquery/dist/jquery.js to work, then you have to either make sure that your express.static() line of code will include that file or you have to define a route specifically for that file. Also, it is sometimes dangerous to use a relative path with no leading / because that makes it relative to the path of your page which is generally not necessary and can make things difficult if you want to serve the same file in lots of different pages on your site.

For example, you could do this in the web page:

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

And, this:

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

Personally, I would probably move jquery.js to a public/scripts directory on my server so I'm not serving anything out of the node_modules directory, so all my publicly served files are centralized in one place so it's entirely clear what can be served to a client and what cannot and so I could design one or two express.static() statements to serve all my public files.



来源:https://stackoverflow.com/questions/44606913/how-to-add-static-file-from-node-modules-after-declare-the-public-as-static

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!