0

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.

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

1 Answers1

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979