Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include static files in express js

I am using the the express js framework with node js and in my server.js file , i have used

app.use('/api',router);

In my ejs file , when i use a script tag

<script src = main.js>

I get an error "Cannot get http://localhost:3000/api/main.js" How can i include these files in the ejs

please help!!!

like image 343
nikhil.g777 Avatar asked Oct 07 '16 08:10

nikhil.g777


2 Answers

You can use express.static middleware

app.use('/public', express.static('directory/containing/your/files'));

The parameter of express.static is the path to the directory containing all your files that you wish to make static (the path that you provide can be relative to the directory where you launch your node process, or an absolute path), the directory should be available in your file system.
Then you can require your resources like: <img src='/public/imagesA.jpg'>
The '/public' mount path is optional, but recommended

like image 113
UnknownFury Avatar answered Sep 30 '22 08:09

UnknownFury


in app.js you have to add static folder directory access

app.use(express.static(path.join(__dirname, 'public')));

in public folder add your folders files

--public
----javascript
----css
----img

inside javascript add your main.js

and in ejs add

<script src = "javascript/main.js"></script>
like image 25
subrahmanya bhat Avatar answered Sep 30 '22 06:09

subrahmanya bhat