How to access and serve the static files in express - node.js

I have a server.js like this:
var express = require('express');
var app=express();
app.get('/',function(req,res){
res.send(index.html); //this is stupid
});
app.listen(3000);
i have the index file in the same directory as that of server.js
Please guide.

Did you look at their docs at all? There's mention of static file serving in the FAQ, for example: http://expressjs.com/faq.html

Write this:
app.use(express.static(__dirname + '/public'));
Put all public static files in /public folder

Related

express.static files dont load static files

I am trying to server static files with express and them dont work, i think its express problem or something but i dont realize why it dont works.
my folders look like this:
app.js
public
--css
--js
--images
and the code i trying to run like this:
app.use(express.static(path.join(__dirname,'public')));
if i do console.log of the path
console.log(path.join(__dirname, 'public'))
i get the next path
C:\Users\J\Desktop\node.js\social-media-cars\public
and if i look at the path with the windows file explorer i see that the path is correct and i see the content inside, so i dont think its path fault
i also tryed :
app.use(express.static(path.join(__dirname,'public')));
app.use('/static',express.static(path.join(__dirname, '/public')));
and dont works, always the same things:
im desesparate with this, idk why this dont works.
code where i use it looks like this:
// Import the express module
const path = require('path');
const express = require("express");
// Instantiate an Express application
const app = express();
const dotenv = require("dotenv").config();
const ActionsRouter = require('./routers/actions-router');
const UserRouter = require('./routers/user-router');
const cookieparser = require('cookie-parser');
// app.use('/static',express.static(path.join(__dirname, '/public')));
//set static files that are rendered after
app.use(express.static(path.join(__dirname,'public')));
//read the cookies from response
app.use(cookieparser(path.join(__dirname, '/public')));
console.log(path.join(__dirname, 'public'))
//create the req.body
app.use(express.json());
//user
app.use("/api",UserRouter);
app.use("/useractions",ActionsRouter);
module.exports = app;
const server = app.listen(port,()=>{
console.log(`listening on port ${port}`)});
get the static files with every response i get
also i get this error
1. Add this middleware in the index.js or app.js above you set view engine
app.use(express.static(path.join(__dirname, "public")));
2. Folder Structure
|__public/
|__ css/
|__ css files...
|__ js/
|__ js files...
3. Import this way
Now you set the path to the public directory you have to give the path public folder when you import
<link rel="stylesheet" href="/css/main.css" />
In the same way, you can import your JS files
You should now be all set up to access CSS or js as well as any file in the public directory
okey i found it, i was so lost because when i try to see the files that i got in each response on the browser, i was not getting any file,
but only when i linked css and html it downloaded the static file, idk why this works like this,
i supposed every of /public file was atached to the response you use it or not
<link rel="stylesheet" type="text/css" href="/css/styles.css">
anyway if there is a way to get the file you request or not i would like to know

How does express know this routing?

I create a simple express server and serve the static files
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Listening on port 3000')
})
When I head to localhost:3000, the index.html in my public directory renders for the route ' / '. I didn't explicitly write the route in my index.js file. How does express know this?
I've tried changing the file name from index.html to random.html and I get an error. CANNOT GET /
As mentioned in the comments, app.use(express.static('public')) is responsible for this. This will essentially serve all files in the public folder you have in the project. If you have an index.html in the public folder, then that will be served at the / endpoint automatically. This is a convention that most websites follow, and is documented in this SO post.
Here is the relevant documentation on express.static(...): https://expressjs.com/en/starter/static-files.html

Find a css file node js

Hi I'm new to nodejs and I've just succeed to deploy a nodejs app online. Now I would like to know how to link CSS, JS or image files be cause when I try to do it like I used to, I get the error GET (not found).
The folder architecture is:
--public
--assets
--css
index.css
--js
--views
--index.ejs
--node modules
app.js
package.json
Assuming that I want to code the link index.css in index.ejs, what I need to write in my app.js file please.
app.js code:
var express = require('express');
var app = express.createServer();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
res.render('index');
});
app.listen(8080,'IP_ADRESS');
index.ejs code:
<link rel="stylesheet" type="text/css" href="/css/index.css">
The basic set up of serving static files in express :
var express = require("express");
var app = express();
...
app.use(express.static(__dirname + '/public'));
...
app.listen(3000);
Now in your .ejs in order to load the css styles or js scripts :
<link rel="stylesheet" href="/css/index.css"/>
First, there's a thing called a static file. Basically, that's a file that's sent over the internet without any kind of modification. Image and CSS files are typically static files.
It looks like you've put your static files in a folder called public.
Express has a built-in feature for sending static files, called express.static. You can use it like this:
// Require the modules we need.
var express = require('express');
var path = require('path');
// Create an Express app.
var app = express();
// Get the path to the `public` folder.
// __dirname is the folder that `app.js` is in.
var publicPath = path.resolve(__dirname, 'public');
// Serve this path with the Express static file middleware.
app.use(express.static(publicPath));
// ...
You should now be able to see static files. If your site is normally accessible at http://localhost:3000, you'll be able to see index.css at http://localhost:3000/css/index.css.
If you want to know way too much about express.static, you can check out a blog post I wrote that goes into Express's static files in depth.

how to set path to the views (template) directory and to static files in node.js

I have created layout.jade, navigation.jade, and index.jade, and I want to glue them together.
In server.js, how do I
set the path to the views (template) directory, and
set the path to static files.
Is it required that node_module be placed in the folder that contains server.js?
Below is the code for server.js:
//create an app server
var express = require("express");
var server = express.createServer();
//set path to the views (template) directory
app.set('views', D:\#Programming\node.js\trial box\views);
//set path to static files
//how is the path to static files set?
app.use(express.static(__dirname + '/../public'));
//handle GET requests on /
app.get('/', function(req, res){
res.render('index.jade', {title: 'web project'});
});
//listen on localhost:3000
app.listen(3000);
Thank you in advance.
This questions a little old, but I'll still leave an answer. You'll need to place your app.use(... statement inside a callback function for app.configure() like so..
app.configure(function(){
app.use(express.static(__dirname + '/../public'));
});
You should use the express bin tool to bootstrap a project you'd get all that setup.
To install it:
sudo npm install express -g

Expressjs not recognizing static files

I have a nodejs app and am using expressjs. I've defined my static directory, but when I access it, it doesn't load. My express config is:
var app = express.createServer().listen(8001);
app.configure(function(){
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.use('/public', express.static(__dirname + '/public'));
app.use(express.cookieParser());
app.use(express.session({ secret: "appsession" }));
app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');
});
Inside my /public directory I have 3 folders, css, js, and img. Inside css I have a style.css. When I try to access it directly via http://localhost:8001/public/css/style.css I get: Cannot GET /public/css/style.css
Any ideas what I could be doing wrong?
Thanks!
EDIT:
It seems to be related to how I have my routes setup. I'm doing it like this:
var routes = require('./routes')(db);
pp.get('/', routes.index);
Then in my index.js file, I have:
module.exports = function(db) {
return {
index: function(req, res, next) {
res.render('index');
}
}
}
I have my error handling enabled, but when I use the routing in this way, it doesn't use expresses error handling, however if I take this out, it does.
You setup the static http middleware as follows:
app.use(express.static(__dirname + '/public'));
And retrieve a file in ./public/css/style.css with the url:
"/css/style.css"
public is not part of the path when you actually request the file.
Change your static handler to this:
app.use('/public/css', express.static(__dirname + '/public/css'));
Then http://localhost:8001/public/css/style.css should get what you want
Full sample app that allows curl http://localhost:8001/public/css/style.css:
app.js
|-public
|-css
|-style.css
var express = require("express"),
app = express.createServer();
app.use('/public/css', express.static(__dirname + '/public/css'));
app.listen(8001);
Was running into the same issue found the answer here
https://github.com/senchalabs/connect/issues/298
When you have try to use nested files it kinda get lost,
it says fixed on the tracker a year ago, however i tried today and worked fine
I figured it out.
I have two services running on my host. Django is running the site at the root: http://myURL.com, and then Node is running at http://myURL.com/node
The configuration is fine with all the files in Node. The index.html file is requested fine, but the index.html when it requests the stylesheets and static files, the request gets caught by Django before it makes it to Node. Django saw the file and had no idea what it is and returned the 404 error.
By disabling Django from catching the requests to those files it all works fine.

Resources