Under my server.js i have the following
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendFile('index.html');
});
app.get('/report', function(req, res){
res.sendFile('report.html');
});
When i start the server and render on http://localhost:8000 i am able to see index.html, but on http://localhost:8000/report i am unable to render report.html and instead i get an path error path must be absolute or specify root to res.sendFile
My directory structure is
public
index.html
report.html
Why i am getting this error?
By default, express.static() will serve up index.html when just / is requested (see reference in the doc). So, your index.html is being served by the express.static() middleware, not by your app.get('/', ...) route.
So, both your app.get() routes would likely have the exact same issue. The first one just isn't being called because your express.static() configuration is already handling that request and sending back index.html.
The /report route is not being handled by express.static() because report is not the same request as report.html. Thus, the middleware does not handle the request so then your misconfigured app.get('/report', ...) handler is invoked and you get the error about it being misconfigured.
This should be all you need:
var express = require("express");
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/report', function(req, res){
res.sendFile(__dirname + "/public/report.html");
});
app.listen(8080);
Or, you can use the path module and join the pieces with path.join():
var path = require("path");
And, then serve the file with this:
res.sendFile(path.join(__dirname, 'public', 'report.html'));
In my own sample nodejs app, either of these res.sendFile() options work.
npm install path
then, you have to specify the root path:
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendFile('index.html');
});
app.get('/report', function(req, res){
res.sendFile('report.html', { root: path.join(__dirname, './public') });
});
app.listen(8000);
Related
How do i stop access to index .html file and let people sign up on home.ejs, i was building a static website but now making a web app and want people to sign up.
i commented out the index section but still the index gets on first instead of home.
I want people to sign up first and then use the app
This is my code.
//jshint esversion: 6
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
/* app.get("/", function(req, res){
res.sendFile(path.join(__dirname, "public", "index.html"));
}); */
app.get("/home", function(req, res){
res.render("home")
})
app.listen(3000);
console.log('now the server is running')
App using static assets from public which includes your index.html file.
You can remove index.html from a static source
app.get("/", function(req, res){
res.sendFile(path.join(__dirname, "views", "index.html"));
});
Or you can give a base path to static folder.
app.use('/public' ,express.static(path.join(__dirname, 'public')));
I use passport.js to authenticate user after he enters login page. To keep user logged in when he returns to home page i'm going to use something like:
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
if(req.user){
// connect to database ....
} else{
res.sendFile(__dirname +'/index.html');
}
});
Note that index.html file is inside "public" folder. Recently i realized that having a code like above, node.js doesn't use app.get('/'....) route but it serves index.html directly. So i'm unable to check if req.user exists. Any suggestion?
As You might understand express.static handles index.html before Your router.
But You cannot avoid express.static also (otherwise You have to use nginx or write own static file output).
So You've to re-think Your folder structure or have to develop 2 separate apps: api (backend) and frontend (that will request to api for data)
In context of Your question I wrote an example app where I organize assets, html files and app routes:
1) Have such folder structure:
2) and example app.js :
'use strict';
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
app.set('trust proxy', 1);
// attaching renderer
app.engine('.html', require('ejs').renderFile); // ejs renderer will render .html files as ejs files
app.set('view engine', 'html'); // views has .html extension
app.set('views', __dirname + '/public'); // views live in public folder
// attaching common middlewares
app.use('/assets', express.static('public/assets')); // our static assets will live in public/assets folder
app.use(cookieParser());
app.use(bodyParser());
// implement and attach passport auth somewhere (:
// remove it after passport has been attached:
const authorizeUser = (req, res, next) => {
req.user = {id: 1, username: 'test'};
next();
};
app.get('/', authorizeUser, (req, res) => {
res.render('index', {user: req.user}); // render get index.html from views folder (see above)
});
app.listen(8080, () => {
console.log('App listening');
});
p.s. download example app from here (don't forget to call npm i inside extracted folder (; )
p.s. implement passport.js Yourself
I am running a very simple node app. I have my app.js in my root folder and my index.ejs, contact.ejs and about.ejs in the views folder.
When I run this on my localhost it works like a charm. I am trying to put the app onto a2hosting but a2hosting it does not find the index.ejs file at all however if i navigate to the about or contact on a2hosting I see them perfectly.
How can I move my index.ejs to my root folder which I suspect is the problem on a2hosting.
Here is my app.js file:
var express = require("express"),
app = express();
app.set("view engine", "ejs");
// app.use(express.static(__dirname + '/public'));
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/css', express.static('css'));
//Root Route
app.get("/", function(req, res){
res.render("index");
});
app.get("/contact", function(req, res){
// res.send("You have reached the contact page");
res.render("contact");
});
app.get("/about", function(req, res){
// res.send("You have reached the contact page");
res.render("about");
});
app.listen(3000, process.env.IP, function(){
// process.env.PORT
console.log("Wayne's Server has started");
});
I have tried moving my index.ejs file to the root folder and tried changing
app.get("/", function(req, res){
res.render("index");
});
to
app.get("../", function(req, res){
res.render("index");
});
and to
app.get("./", function(req, res){
res.render("index");
});
but I cannot get it to work. I assume once I get it working on my localhost I should get it working on the web hosting service.
Any advice will be much appreciated.
You have to create the views folder and in inside that folder create the file.
Your project structure supposed to be:
ProjectDemo
- models
- xyz.js
- views
- index.ejs
- about.ejs
- contact.ejs
- routes
- routes.js
- index.js
I am using node.js and express for my site. I need to be able to direct the user when he clicks a link in index.html.
I have three pages: index.html, presentation.html, join.html all in the public folder.
This is how I did the routing in server.js:
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/_tmp'}));
And this is how I wrote the links in index.html:
<a class="btn" href="/presentation">Presentation</a>
<a class="btn" href="/join">Join</a>
when I run the server I get index.html but when I click one of the links to navigate to the other pages I get this error:
Cannot GET /presentation
When I try to add to server.js this:
app.get('/presentation',function(req,res){
res.render('public/presentation.html' , { root : __dirname});
});
I get this error:
TypeError: undefined is not a function
Here is my App layout:
App
/pulic
indx.html
join.html
presentatio.html
server.js
How can enable navigation?
I used mine and it worked
const express = require("express");
const app = express();
const router = express.Router();
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
var publicPath = path.join(__dirname, 'public');
router.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/"));
});
app.get('/new_deposit', function (req, res) {
res.sendfile(publicPath + '/new_deposit.html');
});
As it is configured, you can access the HTML files directly as files href="/join.html".
If you want to use routes for the static files, try this:
var publicPath = path.join(__dirname, 'public');
app.get('/test', function (req, res) {
res.sendfile(publicPath + '/test.html');
});
I found the error in the routes:
I was using either res.render or res.sendFile
when I used res.sendfile it worked fine.
I am trying to make az ExtJS application with a Node.js server. My server code currently looks like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
When I open localhost:3000 in a browser, the html file is load, but not correctly. Checking in firebug I see that itt cannot find the linked files in html. For example
"NetworkError: 404 Not Found - http://localhost:3000/ext-4/ext-debug.js".
This is quite logical, since the file doesn't exist on that URL. My question would be how to fix this issue, so it could find every single linked file on my filesystem.
I'm clearly doing something wrong or missing something, I am totally new in node.
Doesn't look like you're configuring Express' static file handler.
Try adding this code:
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
It would go right after var app = ... like this:
var express = require('express');
var app = express();
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
And then place your static files under the ./public directory.
You'll want to use some static middleware such as: http://www.senchalabs.org/connect/static.html
note express inherits connect so you can
app.use(express.static(filedir));
Or the full thing:
var express = require('express');
var app = express();
app.use(express.static(filedir));
app.get('/employees', function(req, res){
console.log("hello");
res.send("hello");
});
app.listen(3000);