Ratan
Ratan

Reputation: 129

How to load JS file in html using express server

I have put my js in a public directory and trying to load the js in my HTML but getting an error.


var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
 app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
     res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
    console.log(req.body);
    console.log(req.file);
})
app.listen(3000,()=>{
    console.log("server is up");
})

Here is my HTML code to load the JS:

<script src="/public/web.js"></script>

directory structure

├ public
| └ web.js
├ views
| └ some.ejs
└ server.js

Upvotes: 5

Views: 9405

Answers (2)

Shams Nahid
Shams Nahid

Reputation: 6559

To serve a file from the server to the client, you must declare the directory as a static.

Using express you can do this using,

app.use(express.static('PublicDirectoryPath'))

To fetch the files under the public directory,

<script src="FilePathUnderPublicDirectory"></script>

Updated Code:

Now your server.js file should be

var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
app.use(express.static('public'));
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
 app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
     res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
    console.log(req.body);
    console.log(req.file);
})
app.listen(3000,()=>{
    console.log("server is up");
})

Notice that I declare the public directory as a static directory at line 7.

Since your web3.js is directly under the public directory, in your front end, use

<script src="/web.js"></script>

For more, please check the doc.

Upvotes: 3

Ropali Munshi
Ropali Munshi

Reputation: 2996

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

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

now you can serve static files like js, css and images.

Upvotes: 1

Related Questions