Creating routing for a static site using Express - javascript

I am creating a static site, (HTML, CSS, JS) using nodeJS and express for the server...
I am trying to create routes, so that the user sees /about, as opposed to about.html...
For the main, home page (home.html), it works fine. However, when trying to access the pages using the defined routes via app.get, I keep getting errors - any pointers...
Code is as follows - my styling and JS files ate in the public directory and the HTML files are in the views directory :
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname + '/public')));
app.use(express.static(path.join(__dirname + '/views')));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/home.html');
});
app.get('/about', (req, res) => {
res.sendFile(__dirname + '/views/about.html');
});
app.get('/contact', (req, res) => {
res.sendFile(__dirname + '/views/contact.html');
});
// app.use(express.static('public'));
// app.use(express.static('views'));
// console.log(__dirname);
module.exports = app;
The error I get is :
Cannot GET /views/contact.html

if your foldering is like the following photo you can do like this:
app.get('/about', (req, res) => {
res.sendFile(__dirname + '/views/about.html');
});
app.get('/contact', (req, res) => {
res.sendFile(__dirname + '/views/contact.html');
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/home.html');
});

Related

express.js why is root "/" path not working

I'm learning express.js at the moment. Rigth now, my root "/" path is not working anymore. When I check localhost:3000/ nothing is displayed, just a blank page. I can't figure out why. When I use other pathes like e.g. "/hello" its working. Strangely I copied the code from an udemy lessons and its the exact same code. In the udemy lessons its working.
Where is my mistake? What did I do wrong?
I want localhost:3000/ to display my response "Hello"
const express = require('express');
const path = require('path');
const hoganMiddleware = require('hogan-middleware');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'mustache')
app.engine('mustache', hoganMiddleware.__express)
app.use(express.static(path.join(__dirname, 'public')))
app.get('/hello' , (req, res, next) => {
res.send('Hello from hello');
})
app.get('/', (req, res, next) => {
res.send('Hello')
})
app.listen(3000, () => {
console.log('server is running on ' + 3000);
});

Can get ejs file to render, im using node

I would like to get my ejs file to display on the server ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<html>
<head><title><%= title %></title></head>
<body>
welcome <%= user%>;
</body>
</html>
//////////////////////////////////////////////////////////////////////////////////////
var express = require("express");
var app = express();
var port = process.env.PORT || 3000;
app.set('view engine', 'ejs');
app.get("/", function(req, res){
res.sendFile(__dirname + '/about.html');
});
app.get("/news", function(req, res){
res.sendFile(__dirname + '/news.html');
});
//app.get('/student/:id', function(req, rep){
// rep.render('student', { name : student[req.params.id] , id : req.params.id});
//});
//app.get('/student', function(req, res) {
// res.render('student');
//});
app.get('/', function(req, res){
res.render('student',{user:"John Smith"})
});
app.listen(port);
You have conflicting routes configured for '/'.
Do you want to use a separate route for student? like following
app.get('/student', function(req, res){
res.render('student',{user:"John Smith"})
});
You need to create a views folder, and put your .ejs template in there. For example if you create the file views/student.ejs , then you can use this route to render this ejs file
app.get('/', function(req, res){
res.render('student', {user:"John Smith"})
});
Scotch.io tutorial

Express: Serving static files for defined routes

When I visit mysite.com/verify/myusn the result is a 404 error. When I visit mysite.com/ it serves me the index page as expected.
When I turned on the debugger, I realized Express was trying to serve a static file instead. But it also shows my route being registered properly. Please help me out.
Here is my debugger:
Here is my server.js:
var express = require('express');
var app = express();
var path = require('path');
app.get('/*', function(req, res, next){
next();
});
app.use(express.static(path.join(__dirname , '/_site/') , {maxAge:0}));
app.use('/assets/', express.static(path.join(__dirname , '/_site/assets') , {maxAge:0}));
var routesLogin = require(path.join(__dirname, '/api/routes/users'));
routesLogin(app);
app.get('/', function(req, res) {
res.sendFile( path.join(__dirname , '/_site/landing.html'));
});
app.get('*', function(req, res) {
res.send('404');
});
app.post('*', function(req, res) {
res.send('404');
});
port = process.env.PORT || 3000;
app.listen(port);
console.log('listening on ' + port);
./api/routes/users.js:
module.exports = function(app){
var users = require('../controllers/userController');
app.route('verify/:usn')
.get(users.verifyUSN)
};
./api/controllers/userController.js:
exports.verifyUSN = function(req, res, next){
res.status(200)
.json({
status: 'success',
data: data,
message: 'USN Verified.'
});
}
I believe your problem could potentially be in /api/routes/users.js
module.exports = function(app){
var users = require('../controllers/userController');
// previously app.route('verify/:usn')
app.route('/verify/:usn')
.get(users.verifyUSN)
};
Hope this helps.

ExpressJS - Serving Multiple Web Apps with Different Base Directories on the Same Express Server

I am trying to serve a website with different static directories for different routes.
If a get request is made to the /tools* route, I would like to use the /dist/toolsApp/ directory as the base directory for my frontend code.
If a get request is made to the /net* route, I would like to use the /dist/netIdApp/ directory as the base directory for my frontend code.
If a get request is made to the * route, I would like to use the /dist/homeApp/ directory as the base directory for my frontend code.
I'm having difficulty determining where to insert the app.use(express.static(__dirname + DIRECTORY)); lines of code. I initially was trying the below code, but quickly realized that this code wasn't right because I do not want to merge the directories (they have conflicting file names).
// Tools Routes
app.use(express.static(__dirname + '/dist/toolsApp/'));
app.get('/tools*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/toolsApp/index.html'));
});
app.use(express.static(__dirname + '/dist/netIdApp/'));
// Net-Id Authenticated Routes
app.get('/net*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/netIdApp/index.html'));
});
app.use(express.static(__dirname + '/dist/homeApp'));
// Default Route
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/homeApp/index.html'));
});
I then tried specify a route for each of the app.uses, as shown below. And that only seemed to ever send the last route (I also tried changing the last app.use from '*' to '/' and that didn't change anything). The result of this is that the frontend get requests end up having a '/' appended after the file name, making it so that the Express server interprets the request to be for a directory, not a regular file. I'm really unsure as to why this is happening.
// Tools Routes
app.use('/tools*', express.static(__dirname + '/dist/toolsApp/'));
app.get('/tools*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/toolsApp/index.html'));
});
app.use('/net*', express.static(__dirname + '/dist/netIdApp/'));
// Net-Id Authenticated Routes
app.get('/net*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/netIdApp/index.html'));
});
app.use('*', express.static(__dirname + '/dist/homeApp'));
// Default Route
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/homeApp/index.html'));
});
Lastly, I've tried putting the line within the respective app.get, but that wasn't working correctly (express doesn't send the frontend files).
// Tools Routes
app.get('/tools*', function(req, res) {
app.use(express.static(__dirname + '/dist/toolsApp/'));
res.sendFile(path.join(__dirname + '/dist/toolsApp/index.html'));
});
// Net-Id Authenticated Routes
app.get('/net*', function(req, res) {
app.use(express.static(__dirname + '/dist/netIdApp/'));
res.sendFile(path.join(__dirname + '/dist/netIdApp/index.html'));
});
// Default Route
app.get('*', function(req, res) {
app.use(express.static(__dirname + '/dist/homeApp'));
res.sendFile(path.join(__dirname + '/dist/homeApp/index.html'));
});
Could someone help me determine what the best way to do this is?
Node: v8.11.2
Express:
Was able to resolve the issue, the following code did work, it just puts the files in the address.com/tools/, address.com/net/, and address.com/, respectively.
// Tools Routes
app.use('/tools*', express.static(__dirname + '/dist/toolsApp/'));
app.get('/tools*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/toolsApp/index.html'));
});
app.use('/net*', express.static(__dirname + '/dist/netIdApp/'));
// Net-Id Authenticated Routes
app.get('/net*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/netIdApp/index.html'));
});
app.use('*', express.static(__dirname + '/dist/homeApp'));
// Default Route
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/homeApp/index.html'));
});

express (4.0) custom middleware runs on both instances of router even though it's only declared for one

I'm using the code below to learn a bit about the new express.js (4.0). I can't seem to understand why the logging is happening regardless of which path I hit with my browser. Shouldn't it only log for website.get and not for api.get paths?
// Express 4.0 test...
var express = require('express');
var app = express();
var website = express.Router();
var api = express.Router();
var port = process.env.PORT || 3000;
website.use(function (req, res, next) {
console.log(req.method, req.url);
next();
});
website.get('/', function (req, res) {
res.send('Home page');
});
website.get('/about', function (req, res) {
res.send('About page');
});
api.get('/', function (req, res) {
res.send({'json':'response'});
});
api.get('/user', function (req, res) {
res.send({'user':'john'});
});
// app.get('/', function (request, response) {
// response.writeHead(200, {"Content-Type": "text/html"});
// response.end("<h1>Hello, World!</h1>");
// });
app.use('/', website);
app.use('/api', api);
app.listen(port);
console.log('http(s) server revved up on port ' + port);
Any help would rock!
Update: I see, because '/api' matches '/', website gets applied to all routes. Is there any way to avoid this?
probably define the /api router first and the other one - second.
app.use('/api', api);
app.use('/', website);

Categories