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!!!
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!!!
Share Improve this question edited Oct 7, 2016 at 8:19 nikhil.g777 asked Oct 7, 2016 at 8:16 nikhil.g777nikhil.g777 9043 gold badges12 silver badges24 bronze badges 5-
why are you including your bootstrap css file with a
script
tag in the first place? Why don't you use<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
and reference it directly instead of having a static file? – ZombieChowder Commented Oct 7, 2016 at 8:18 - 1 stackoverflow./questions/18629327/adding-css-file-to-ejs you may find ans here.... – Umakant Mane Commented Oct 7, 2016 at 8:20
-
app.use
try changing it toapp.get('/api',function(req,res){ res.send('Huston we have lift off'); });
– ZombieChowder Commented Oct 7, 2016 at 8:23 - Possible duplicate of Express-js can't GET my static files, why? – Ben Fortune Commented Oct 7, 2016 at 8:25
- @UmakantMane Thanks a lot ! I used app.use(express.static(__dirname + '/public')); It works perfectly! – nikhil.g777 Commented Oct 7, 2016 at 8:27
3 Answers
Reset to default 6in 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>
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 remended
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.