nodejs sendfile html page - html

I have this code that allows me to open a HTML page from specific folder, if I use server.js to open that HTMLpage so the page it is generating with all the css and jquery files but if I try to move the get statement to the routes folder then the page is generated but without any css and jquery files and I don't know why !
what I did in the server.js for the generation of the HTML page is below which is working perfectly :
const folderPath = __dirname + '/public/AppTemplate/src'
app.use(express.static(folderPath))
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/public/AppTemplate/src/index.html'));
});
but what I'm trying now is to get the html page from routes.js :
step 1 :
I implemented this statement in server.js
app.use('/users', require('./backend/routes/profile.routes.js'));
step2 :I tried this statement in routes.js with simple modification :D :
router.get('/profile', function (req, res) {
const dirname = __dirname;
console.log(dirname)
const newpath = dirname.length - 14;
const newP = dirname.substring(newpath, dirname.lastIndexOf("/"));
console.log(newP);
res.sendFile(path.join(newP+ '/public/AppTemplate/src/02-ProfilePage.html'));
});
the step 2 is working but I couldn't get all the associated files (jquery css ...) which are located in
/public/AppTemplate/src
the image of the output is below :
hope I mentioned everything,
Best Regards,

It's because of the content in the 02-ProfilePage.html has an incorrect path.
Check the path in the script tags. If there is a slash it means that it's already in the /public/AppTemplate/src which you specified.
For example, /js/file.js will actually point to /public/AppTemplate/src/js/file.js
Perhaps try adding a / in front of your path in the script tag.
Example:
/css/x/y/z/ instead of css/x/y/z
You will have to append a / to all the routes in your script/link tag to be able to successfully load the local resources.
You can use the find and replace functionality in your code editor or IDE to speed up the process if possible.

Related

Trying to load my html file using nodejs to create login page

I am trying to use node.js to run a html file. I already have a login.html and styles.css for for the login page but now I don't know how to use the node js file to run my login.html page. I follow this youtube tutorial to make the a login authentication. It seems to have everything needed but now I dont know how to use it in my login.html file.
I need help modifying this so that I can run my login.html file.
index.js file
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const postRoute = require('./routes/posts');
//Import Routes
const authRoute = require('./routes/auth');
dotenv.config();
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log('Connected to DB')
);
//Middleware
app.use(express.json());
//Routes Middlewares
app.use('/api/user', authRoute);
app.use('/api/posts', postRoute);
// start listening
app.listen(3000, () => console.log('Server up and running port:3000'));
I am new to node.js and am completely lost on how to solve this problem.
you can solve it in two ways, first you can install view engine like ejs and use res.render (if you want more about it i can explain)
Second you can response with the HTML file like this: (works only with express and you have express)
app.get('/yourRotue', function(req, res, next){
res.sendFile(__dirname + '/yourPath/htmlFile.html');
});
How to use EJS (basic):
First please install EJS with npm install ejs install body parser npm install body-parser
now you need to create two folders on the root folder, public and views.
inside views you can create a folder auth and put your EJS files there.
then on your app.js (or index.js, the main file) add view engine middleware:
(*notice that you dont need to require ejs, also notice you dont need to install path its built in with node)
//import body parser on top (to parse json/urlencoded/text..
const bodyParser = require('body-parser');
//import path so you can use it for the public folder
const path = require('path');
//this line makes public folder public so you can store js/css/image...
app.use(express.static(path.join(__dirname, 'public')));
//use the body parser as middleware
app.use(bodyParser.json({ limit: '200mb' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text({ limit: '200mb' }));
//this line tells node js to use ejs
app.set('view engine', 'ejs');
//this line make sure that the views folder is the folder with the ejs files
app.set('views', 'views');
//now your route will look like this:
app.get(/routeName, (req,res,next) => {
let example
//you return response with render, to render the file you want.
// you dont write the views folder name, only the file name without .ejs
// elso you can run functions here and later send the response to the front end
function(){
example = 1 + 1 * 5
}
// *very often the function above is to find something in the db
return res.render('auth/ejsFileName', {
pageTitle: 'some page title for the example',
exampleKey: example
})
})
I can suggest you to use mvc (models, views, controllers) structor, if you want to know more about it you can open new question or to search about it.
EJS:
put your css and js in public folder, you can create js folder and css folder inside the public folder and then put the css in js in their folder.
*notice you dont need to write ./public in the route.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/someCssFile.css">
<!-- here is the title that comes from the back end -->
<title><%= pageTitle %></title>
</head>
<main>
<h1>Here you can see the example with the function<%= exampleKey %></h1>
</main>
<script src="/js/someJsFile.js"></script>
</body>
</html>
the file look like html but it has .ejs
there is many things you can do with ejs like to loop through values.. i would suggest to learn a bit more.
this is the basic it should work.
For the post request i need to know if you are posting a form as urlEncoded or json. so i can show you how it should look like.
You can try to use some template engines like Handlebars. https://youtu.be/1srD3Mdvf50 You can try to follow this tutorial in order to load some html from the server side. Then you can use different selectors in order to interact with DOM elementa

Express server loads html page with/without css/js when last route character is without/with '/', respectively

The following is affecting my second html page model.html:
If my route address is with a '/ at the end (typed on browser addr field) like so: http://localhost:3002/home/model/ then the correct html page is loaded, but no css/js is loaded.
If my route address is without a '/ at the end like so: http://localhost:3002/home/model then the correct html page is loaded, and css/js is loaded.
Without '/' at the end, css/js loads fine using statics/css/style.css and js/dynamicData.js
The weird part is that when '/' is at the end, I can use ../statics/css/style.css to load the css and "../js/chartData.js" to load js - but that means the one without '/' now longer loads the css/js.
My folder structure:
js - has other js scripts
node_modules
statics
css - has style.css
image - has images
index.html
model.html
index.js - init express server
pc_server.js - express server
Express code (pc_server.js)
Middleware setup?:
process.chdir(__dirname);
// base = '/home'
app.use(base, express.static(__dirname));
Routes:
const INDEX_PAGE = '/';
const MODEL_PAGE = '/home/model';
function setupRoutes(app) {
const BASE = app.locals.base;
app.get(INDEX_PAGE, redirectHome(app));
// BASE = '/home'
app.get(BASE, toHomePage(app));
app.get(MODEL_PAGE, toModelPage(app));
Routes functions defined:
function redirectHome(app) {
return errorWrap(async function(req, res) {
try {
res.redirect(app.locals.base);
}
catch (err) {
console.error(err);
}
});
}
function toHomePage(app) {
return errorWrap(async function(req, res) {
try {
res.sendFile(path.join(__dirname+'/statics/index.html'));
}
catch (err) {
console.error(err);
}
});
}
function toModelPage(app) {
return errorWrap(async function(req, res) {
try {
res.sendFile(path.join(__dirname+'/statics/model.html'));
}
catch (err) {
console.error(err);
}
});
}
The goal is to load the same page with css/js with either http://localhost:3002/home/model/ or http://localhost:3002/home/model
Additional: Why is it that when I type http://localhost:3002/home I get http://localhost:3002/home/ automatically on my browser addr field?
the problem
it probably occurs due to relative links in your site.
when home/model is used - relative css/style.css link will lead to home/css/style.css
when home/model/ is used, the same link will lead to home/model/css/style.css
the solution:
the easiest way to solve it is changing your link tag to:
<link rel="stylesheet" type="text/css" href="../../home/statics/css/style.css">
this link goes to the root address, and then enters your path Independently from the user's path.
why it's working?
the ../../ prefix tell the browser to go two levels up.
the browser consider the "home/model/" as a visit inside a model folder inside home folder. two levels upward lead the browser to the root level, where it has a clean start.
when the user visits "home/model", it considered as a file inside the home folder. one level upward is the root level, and the second ../ does nothing.
after achieving the root level - the browser entering "home/statics/css/style.css" and find the right file in both cases :)

file accessing issue in Nodejs and trouble shoot while displaying json content [duplicate]

If I do a
res.sendfile('public/index1.html');
then I get a server console warning
express deprecated res.sendfile: Use res.sendFile instead
but it works fine on the client side.
But when I change it to
res.sendFile('public/index1.html');
I get an error
TypeError: path must be absolute or specify root to res.sendFile
and index1.html is not rendered.
I am unable to figure out what the absolute path is. I have public directory at the same level as server.js. I am doing the res.sendFile from with server.js. I have also declared app.use(express.static(path.join(__dirname, 'public')));
Adding my directory structure:
/Users/sj/test/
....app/
........models/
....public/
........index1.html
What is the absolute path to be specified here ?
I'm using Express 4.x.
The express.static middleware is separate from res.sendFile, so initializing it with an absolute path to your public directory won't do anything to res.sendFile. You need to use an absolute path directly with res.sendFile. There are two simple ways to do it:
res.sendFile(path.join(__dirname, '../public', 'index1.html'));
res.sendFile('index1.html', { root: path.join(__dirname, '../public') });
Note: __dirname returns the directory that the currently executing script is in. In your case, it looks like server.js is in app/. So, to get to public, you'll need back out one level first: ../public/index1.html.
Note: path is a built-in module that needs to be required for the above code to work: var path = require('path');
Just try this instead:
res.sendFile('public/index1.html' , { root : __dirname});
This worked for me.
the root:__dirname will take the address where server.js is in the above example and then to get to the index1.html ( in this case) the returned path is to get to the directory where public folder is.
An alternative that hasn't been listed yet that worked for me is simply using path.resolve with either separate strings or just one with the whole path:
// comma separated
app.get('/', function(req, res) {
res.sendFile( path.resolve('src', 'app', 'index.html') );
});
Or
// just one string with the path
app.get('/', function(req, res) {
res.sendFile( path.resolve('src/app/index.html') );
});
(Node v6.10.0)
Idea sourced from https://stackoverflow.com/a/14594282/6189078
res.sendFile( __dirname + "/public/" + "index1.html" );
where __dirname will manage the name of the directory that the currently executing script ( server.js ) resides in.
Based on the other answers, this is a simple example of how to accomplish the most common requirement:
const app = express()
app.use(express.static('public')) // relative path of client-side code
app.get('*', function(req, res) {
res.sendFile('index.html', { root: __dirname })
})
app.listen(process.env.PORT)
This also doubles as a simple way to respond with index.html on every request, because I'm using a star * to catch all files that weren't found in your static (public) directory; which is the most common use case for web-apps. Change to / to return the index only in the root path.
I tried this and it worked.
app.get('/', function (req, res) {
res.sendFile('public/index.html', { root: __dirname });
});
process.cwd() returns the absolute path of your project.
Then :
res.sendFile( `${process.cwd()}/public/index1.html` );
you can use send instead of sendFile so you wont face with error!
this works will help you!
fs.readFile('public/index1.html',(err,data)=>{
if(err){
consol.log(err);
}else {
res.setHeader('Content-Type', 'application/pdf');
for telling browser that your response is type of PDF
res.setHeader('Content-Disposition', 'attachment; filename='your_file_name_for_client.pdf');
if you want that file open immediately on the same page after user download it.write 'inline' instead attachment in above code.
res.send(data)
Another way to do this by writing less code.
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile('index.html');
});
If you want to set this up once and use it everywhere, just configure your own middleware. When you are setting up your app, use the following to define a new function on the response object:
app.use((req, res, next) => {
res.show = (name) => {
res.sendFile(`/public/${name}`, {root: __dirname});
};
next();
});
Then use it as follows:
app.get('/demo', (req, res) => {
res.show("index1.html");
});
I use Node.Js and had the same problem... I solved just adding a '/' in the beggining of every script and link to an css static file.
Before:
<link rel="stylesheet" href="assets/css/bootstrap/bootstrap.min.css">
After:
<link rel="stylesheet" href="/assets/css/bootstrap/bootstrap.min.css">
The following worked for me
res.sendFile(path.resolve(__dirname,'./path_to_file_from_current_directory'));
Worked for me:
res.sendFile("./public/filename.ext", { root: "./" });

Setting up URL base for JSON with expressjs

I am completely new to node ExpressJS and am required to rewrite a rule for my server data source (jason format).
./
../public/
/public/css
/public/js
/public/index.html
../datasource/
/datasource/carmodel.json
The default static directories are set in:
app.use(express.static(__dirname + '/../public'));
The above work and everything runs under the 3000 port fine locally.
I need to rewrite the URL for my json file (datasource/carmodel.json) by replacing datasource with car/models/. However my application is unable to find the /datasource/carmodel.json file. I have attempted to recreate this via the following:
app.use('car/models/', require('./../datasource/'));
But I still cannot find the json source URL. It does not matter if I type: http://localhost:3000/car/models/carmodel.json or http://localhost:3000/datasource/carmodel.json for that matter. Is there something I am missing?
------------------
EDITED
------------------
Please see my project structure:
./
node_modules/
public/
css/
custom.css
js/
app.js (angular)
index.html
datasource/
carmodel.json
index.js (express file)
package.json
README
Currently my static folder is running of localhost:3000/. Contents of datasource/index.js:
var express = require('express');
var app = express();
app.use(express.static('public'));
//json
app.get('/car/models/:filename', function(req, res){
var filename = req.params.filename;
var fileDir = 'server/' + filename;
res.download(fileDir);
})
app.listen(3000, function(){
console.log('App started on port 3000!');
});
check something like this:
app.get('/car/models/:filename', function(req, res){
var filename = req.params.filename;
var fileDir = __dirname + '/datasource/' + filename;
res.download(fileDir);
})
then this http://localhost:3000/car/models/carmodel.json should work. I dont test it, youst write from head, therefore there may be some typos.
My solution is not safe. You shoud validate 'filename' before production use (all data from user must be validated).

Express routing returns undefined randomly

I am trying to learn Express with NodeJS and would like to render my views with plain HTML. I hacked together a webserver based on the Express API documentation and several Stack questions, particularly the answer by Andrew Homeyer in this question which states
You can have jade include a plain HTML page:
in views/index.jade
include plain.html in views/plain.html
... and app.js can still just render jade:
res.render(index)
My directory structure looks like this
Project
*web.js
Public
img
js
lib
gallerific
*jquery.opacityrollover.js
*jquery.gallerific.js
angular
theme
views
partials
*index.html
*index.jade
and my server looks like this.
var express = require('express'),
jade = require('jade');
var app = module.exports = express();
app.configure(function(){
app.set('views', __dirname + '/public/views');
app.use("/public/lib", express.static(__dirname + "/public/lib"));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.set('view engine', 'jade')
app.use(express.bodyParser());
});
app.get('/', function(req, res) {
res.render('index');
});
app.get('/partials/:name', function(req, res){
var name = req.params.name;
res.render('/public/partials/' + name);
});
app.get('/public/data/:name', function(req, res){
var name = req.params.name;
res.json('/public/data/' + name)
});
app.listen(3000, function(){
console.log("Express app listening on port %d in %s mode", this.address().port, app.settings.env);
});
What I am seeing is that certain files fail to load from directories in which everything else loads just fine. For example, my Gallery page fails to load the jquery.gallerific.js javascript file from my lib/gallerific directory while it does load the jquery.opacityrollover.js. I have poked around with Chrome Developer Tools and see the following
I had this site working with the Angular Bootstrap webserver so it doesn't seem to be a javascript error with the client side code. Does anyone know what I might doing that would cause this problem?
The source is available at https://github.com/jamesamuir/express-simple-html.git
I figured it out. It turns out I had to resolve paths that I had forgotten about so that Express could render them correctly. It wasn't that the Gallerific javascript library didn't load, it was throwing an error on the image source of undefined for my gallery images (I am pulling them from a JSON file).
Once I put the appropriate paths in for the images and the data file, everything started working again. Thanks to everyone who provided a suggestion for me. It really helped me to work through the problem.