5

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!!!

nikhil.g777
  • 882
  • 3
  • 12
  • 24
  • why are you including your bootstrap css file with a `script` tag in the first place? Why don't you use `` and reference it directly instead of having a static file? – ZombieChowder Oct 07 '16 at 08:18
  • 1
    http://stackoverflow.com/questions/18629327/adding-css-file-to-ejs you may find ans here.... – Umakant Mane Oct 07 '16 at 08:20
  • `app.use` try changing it to `app.get('/api',function(req,res){ res.send('Huston we have lift off'); });` – ZombieChowder Oct 07 '16 at 08:23
  • Possible duplicate of [Express-js can't GET my static files, why?](http://stackoverflow.com/questions/5924072/express-js-cant-get-my-static-files-why) – Ben Fortune Oct 07 '16 at 08:25
  • @UmakantMane Thanks a lot ! I used app.use(express.static(__dirname + '/public')); It works perfectly! – nikhil.g777 Oct 07 '16 at 08:27

3 Answers3

5

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>
subrahmanya bhat
  • 588
  • 3
  • 11
4

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

tu4n
  • 4,200
  • 6
  • 36
  • 49
UnknownFury
  • 304
  • 1
  • 12
3

You serve static files through an included middleware in Express - express.static('folder/with/resources'). You do so by adding it to the middleware chain using app.use.

Let's say you want to serve your static files located in the local folder /dist through the public URL /static.

import express from 'express';
const app = express();

app.use('static', express.static('dist'));

Read more about it here.

Kris Selbekk
  • 7,438
  • 7
  • 46
  • 73