How to serve folder in 'public' with express - javascript

I am trying to serve the login page in my public folder in express, so far i have been unable to do so. I tried to work the path but I don't know why it does not work. What I want to have is that I can have more code in the callback but because of the way it is now I can do that, when I try to make the callback a full function it won't work either.
My folder structure
- root
- server
- server.js
- public
- login
- index.html
const express = require('express');
const app = express();
const path = require('path');
app.listen(4000);
console.log('server started\n');
app.get('/', () => app.use(express.static(__dirname + '/public/login')));
// what i want to have
app.get('/', () => {
// serve file
});

You should mount the static file serving directly when the server starts, not after the first request arrives so this line:
app.get('/', () => app.use(express.static(__dirname + '/public/login')));
has to be:
app.use(express.static(__dirname + '/../public/login'));
You also have to go up one folder as the code is started in the /server/ directory, which can be done with /../.
If you only want to server the index.html from public folder instead of all files in there, what you can do is
app.get('/', (req, res) => res.sendFile('index.html', { root: __dirname + '/../public/login'));

Related

Can't set static folder express.js

I'm trying to set a static folder for my index.html file and other folders like css, img and js scripts.
but i don't manage to set a static folder successfully.
this is my app.js code:
const path = require('path');
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, 'httpdocs')))
// app.get('/', (req, res) => {
// res.sendFile('index.html')
// });
const PORT = process.env.PORT || 5000
app.listen(PORT, (err) => {
if (err) {
console.log(err);
}
console.log(`Listening on port ${PORT}`);
})
my file tree is like this:
---node/
------httpdocs (i want this to be static folder
---css/
---js/
---img/
--index.html (this file should be loaded when loading the root link)
---app.js (nodejs script)
p.s: im using plesk on windows so if this makes any difference tell me.
I can see the only error is in below line.
app.use(express.static(__dirname + 'httpdocs'))
Try to print below tow different method using console :
console.log(__dirname+ 'httpdocs');
console.log(path.join(__dirname, 'httpdocs'));
Output:
...\nodehttpdocs
...\node\httpdocs
I hope you get the solution.
If you are trying to manually merge path then you have to add path separator '\' externally
Ex: app.use(express.static(__dirname + '\httpdocs'));
Or else use below method
Ex: app.use(express.static(path.join(__dirname, 'httpdocs')));
I suggest using path.join method. Because it will add path separator based on the operating system. Or else you have to manage manually.

Different Path for Serving Static HTML files in Express

Just a quick question. Say I have 2 different static HTML files that I want to serve in Express, index.html and contact.html. I've been fiddling around and I currently use this barebone Express code to serve them:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static('public'))
app.get('/', function (req, res) {
res.sendFile('/index.html');
});
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/public/contact.html');
});
app.listen(3000, function () {
console.log('runnning on port 3000')
});
Question is, I tried to serve contact.html using
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
but it always resort to the root directory instead of the public directory. OTOH, I can server index.html just fine without having to explicitly adding /public in the response.
Can anybody point me what's the cause for that?
Thanks.
For the given file structure:
yourapp
|-- contact.html
|-- index.html
`-- server.js
The following code would work just fine:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
Assuming both index.html and contact.html have read access.
Remember, sendFile requires an absolute path and __dirname refers to your app directory. Make sure you give references according to your file location.

node server.js - Cannot GET /

I am currently working on a project which is a webpage using angular to dynamically change DOM elements. Within the project is a public folder which contains all HTML, CSS, JavaScript and JSON objects. The project must be distributed so I am using node to run from localhost. This is my server.js code:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req,res){
res.sendFile(path.join(__dirname + '/public'));
});
app.listen(8080, function(){
console.log((new Date()) + " Server is listening on port 8080");
});
When I head to localhost:8080 it just says Cannot GET /. Where am I going wrong?
The correct way to serve static files with express is as follows:
//Look for statics first
app.use(express.static(path.join(__dirname, 'public')));
//Return the index for any other GET request
app.get('/*', function (req, res) {
res.sendFile('index.html', {root: path.join(__dirname, 'public')});
});
Edit: on a side note this may be worthwhile to mention that app.get should be the last route declared in node so if you want API endpoints exposed declare them above (before) the final app.get.
You forgot to point to the actual html file you want to display. If you have a index.html in your public directory, just point tot '/public/index.html' . That works (tested it here).
Followed user Muli's answer and all files are now being served correctly. Code here:
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req,res){
res.sendFile('index.html', {root: path.join(__dirname, './public')})
});
app.listen(8080, function(){
console.log((new Date()) + " Server is listening on port 8080");
});

Loading HTML files in Nodejs

I am trying to load HTML files in nodejs. In public folder, I have two html files test.html and index.html. I would like to use nodejs to showcase the pages, but its working for index.html and for the case of test, it shows an error saying that res.sendFile is not a function.
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});
// viewed at http://localhost:8080
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname + '/public/test.html'));
});
app.listen(8080);
For serving static files such as JS, CSS, images, html files, you can use the express.static built-in middleware function in Express.
Serving static files in Express
Say if your 'Public' folder has some JS, html files which is required at client side. Then you need do to go like this :-
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
var server = app.listen(8080);

Node JS - HTML Paths

I recently have the problem that I dont get how the paths for html in node js work. I link my index.html's scripts as normal - relative to the index.html's file (node.js file and index.html are in the same directory "res.sendFile(__dirname + '/index.html');"). But if I open it up in the Browser executed with node js it just stats "cant GET blabla" for the scripts. Instead opening it up by just clicking index.html without node js those paths work! How do I have to write html paths for node js?
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
port = Number(process.env.PORT || 3000),
server.listen(port);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
Thanks for your time! :)
Look at this:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
You have told Node "When the browser asks for / give it index.html".
What happens when the browser asks for someScript.js?
You haven't told Node what to do then.
(You'll probably want to find a library for serving up static files rather than explicitly handling each one individually).
you should configure express to server static files, for example, put all the static files under a directory called 'public'
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
ExpressJS to Deliver HTML Files
Render HTML file in ExpressJS
You can use
app.use(express.static(path.join(__dirname, "folder-name")));
Usually i put all my static files in a separate folder named "assets"
The I set up a static route as shown below:enter code here
app.use('/assets', express.static('assets'));
When you write:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
It will only serve index.html file, not the other js scripts and stylesheets which you have added in your html.
There are 2 ways to solve that:
For both of them, I would suggest to use 'path' module.
Solution 1:
var path = require('path')
app.get('/path/to/js/foo.js',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/js/foo.js')
})
app.get('/path/to/css/bar.css',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/css/bar.css'))
})
and so on for every .css and.js file you have added in your index.html.
Solution 2:
You can create a public dir in your project's root dir. Inside which all your img, css and js files will be there.
Next,
var path = require('path')
app.use(express.static('public'))
app.get('/',function(req,res){
res.sendFile(path.resolve(__dirname,'/index.html')
})

Categories