I have a basic project set up with server.js in my root with this code:
app.use('/', express.static(__dirname + '/public/'));
Additionally I have a public folder with index.html, styles and scripts folder in that dir root.
I'd like my web application to send users to index.html regardless of any url paramaters they might have. For example: If a user tries to go to localhost:8888/notarealpage it still loads index.html (without a redirect) so I can still reference the 'notarealpage' in the location.href property.
You can use:
app.get('*', function (req, res) {
res.sendFile(path.resolve(__dirname, 'public/index.html'));
});
This way, it will send your index.html no matter the URL.
Please notice you might have to fine tune the sendFile parameter.
Adding
app.get('*', function (req, res) {
res.sendFile((__dirname + '/public/index.html'));
});
to the end of my routes in server.js did the trick.
Related
I have static 3 HTML pages and the pages are running on localhost:3000. I inserted the links in HTML, so that clicking on them I can switch from this page to another one. And I wrote the code in my js file like this:
app.use("/bbb.html", function (req, res, html) {
res.sendFile(__dirname + "/bbb.html");
});
app.use("/", function (req, res, html) {
res.sendFile(__dirname + "/index.html");
});
app.use("/ccc.html", function (req, res, html) {
res.sendFile(__dirname + "/ccc.html");
});
In all of the HTML pages I added corresponding links in this format:
The first 2 codes work, but the 3rd one which has to take to ccc.html doesn't work.
I assume it does not work because on that page where I have placed the link, there are 4 same anchor tags. So probably I have to specify this in the third code.
How is it possible? (I am a beginner)
Thank you!
Let's attempt to clean this up and solve a bunch of problems:
app.get("/bbb", function (req, res) {
res.sendFile(__dirname + "/bbb.html");
});
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.get("/ccc", function (req, res) {
res.sendFile(__dirname + "/ccc.html");
});
And, then the links in your pages that come from this same server:
bbb
index
ccc
Things I changed:
Use app.get() instead of app.use() for simple GET requests.
Make the links in the <a> tags href match the route definitions exactly.
Fix the arguments to app.get() - there should not be an argument named html. If you planned on using the third route argument, it should be called next, but if you're not planning on using it, the convention is to not declare it.
The reasons to not use app.use() for simple GET requests are as follows:
app.use() accepts partial path matches. You don't want that because / will conflict with /ccc unless you have strict ordering and you don't want partial matches for these simple routes.
You only want to respond to GET requests, not POST, PUT, DELETE, etc... with these routes.
FYI, with the proper directory structure on the server, all these files could be served with one line of code using the express.static() middleware. There is generally no need to individually code multiple static routes like this.
you are using app.use('/') before app.use('/ccc.html') so when you write localhost:3000/ccc.html on URL it first checks to /bbb.html no it is not matching then it checks to / yes it will be a match because it checks if the prefix is match or not..so you will be serve up app.use('/') not app.use('/ccc.html')
solution..
write app.use('/ccc.html') before app.use('/')
const express = require('express');
const app = express();
app.use("/bbb.html", function (req, res, html) {
res.sendFile(__dirname + "/bbb.html");
});
app.use("/ccc.html", function (req, res, html) {
res.sendFile(__dirname + "/ccc.html");
});
app.use("/", function (req, res, html) {
res.sendFile(__dirname + "/index.html");
});
app.listen(3000,()=>{
console.log('server is up on port: ',3000)
});
and one important thing use is for different purpose.. there is a saying
"Incomplete knowledge is dangerous". Go and complete the full tutorial from wherever you are learning node js
I am developing an application and I have defined my custom routes in a different way. I am using Web Storm IDE to develop and it has a specific folder of routes where all the routes are kept individually. I have the following code in my directory /routes/about.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('about', { title: 'About Us' });
});
module.exports = router;
Now in the app.js I have written the following code to include these route and use it:
var index = require('./routes/index');
var users = require('./routes/users');
var about = require('./routes/about');
app.use('/', index);
app.use('/users', users);
app.use('/about', about);
But when I click on about link, it does not open the page. Though, if I write the route in the app.js file directly as:
app.get('/about', function (req, res) {
res.render('about');
});
then it renders the page. Also, if I do not make separate routes and use the default routes file (/routes/index.js) and include this in that file, then also the code works fine. Can anyone explain or tell is there any mapping of these route files done which is missed by me, or I am doing something syntactically wrong
You probably created a route for /about/about. To fix, change the about router from this:
router.get('/about', ...);
to this:
router.get('/', ...);
This, then goes with:
app.use('/about', router);
which already includes the /about path. Everything in that router will already have /about at the beginning of the path.
Use below code in about file
app.get('/', function (req, res) {
res.render('about');
});
You have already defined '/about' route in main file so if you want to render page on '/about' so you need to define route like this '/' in about page.
For example route '/about/us' then function will be in about page :
app.get('/us', function (req, res) {
res.render('about us');
});
The method to redirect the route is correct, but you have not pass the route to app.
so you just need to do is ,
router.use('/about', about);
app.use('/', router);
Like wise add router in app
I have a login page called login.html and an index page called index.html. I want to make a authentication and that only a connected user can access the index page.
I did not implement the post method on the login HTML page. I have to manually send the login username and password by going on this url:
http://localhost:2222/?username=a&password=b
Everything worked but I could not see my css, js and some other files in the index.html. To solve this problem I added this at the beginning of my code:
app.use(express.static(__dirname));
The problem is that now if I go to the localhost:2222 it shows the index.html file instead of the login.html file. Even if I use:
app.get('/', function (req, res) {
res.redirect('/login');
});
How does it come ? How can I solve this ?
The full code is:
var express = require("express");
var port = process.env.PORT || 2222;
var app = express();
app.use(express.static(__dirname));
var session = require('express-session')
app.use(session({
secret: 'keyboardcat',
resave: true,
saveUninitialized: true
}));
function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.sendfile('login.html');
} else {
next();
}
}
app.get('/', function (req, res) {
res.redirect('/login');
});
app.get("/login", function(req, res) {
if (req.query.username === 'a' && req.query.password === 'b') {
req.session.user_id = req.query.username;
res.redirect('index');
} else {
res.sendfile('login.html');
}
});
app.get('/index', checkAuth, function(req, res){
res.sendfile('index.html');
});
app.get('/logout', function (req, res) {
delete req.session.user_id;
res.redirect('/login');
});
My file tree is as follow: index.html, login.html and server.js are in a folder called server. In this folder sever are also 4 folders: JS, CSS, Images and Random.
You are using project folder for static as you posted app.use(express.static(__dirname));. ExpressJS using index.html as default index page. So you need to rename index.html to something else like main.html and use res.sendfile('main.html');.
Alternate Solution:
Create a folder say public and put all static content(js, css and images) into public folder and please do not put html file into public folder and use app.use(express.static(__dirname) + '/public');.
It is very important that you fix your directory structure if you're using express.static, because at this moment, it is possible to run http://localhost:2222/server.js and download the server files, which is where you currently store your secrets.
What I recommend you to do is create a server/static directory, and place all HTML, CSS, JS, images and other assets inside, and then change this line
app.use(express.static(__dirname));
to
app.use(express.static(__dirname + '/static'));
Additionally, you should never, ever send auth data through GET parameters like you currently do with http://localhost:2222/?username=a&password=b. You need to change this route into a POST request, by editing this line:
app.get("/login", function(req, res) {
to
app.post("/login", function(req, res) {
You might need to change your form in the HTML from <form method="get" ...> to <form method="post" ...>
You have to define the root directory as a first parameter for serving static content:
app.use('/', express.static(__dirname));
Or alternatively you can use:
app.use(express.static(__dirname + '/'));
I have a page asking for these files
<link rel="stylesheet" href="/vendor/css/style.css">
<script type="text/javascript" src="/vendor/js/app.js"></script>
and I've set up the express static route as follows
express = require 'express'
app = express()
app.use '/vendor/js', express.static './node_modules/framework/'
app.use '/vendor/css', express.static './otherFramework/'
app.get '/page/:num', (req, res) ->
page = parseInt req.params.num, 10
res.render 'list', #list is a jade file that extends a common layout.jade, the same as the '/' route
start: page
end: ++page
return
when I open the page '/' everything works fine, but now I want to implement another MVC-like route like '/page/:num', and express is asked this new route as base path for my requested external files, ex: (from the server log)
/page/1/vendor/css/style.css - 200
and this obviously doesn't work.
How can I tell express to search in the root? I tried to use a ~ before the path but it didn't work.
in the app.js (main file) file,before application routes, add these lines :
app.get('*/vendor/css/style.css', function (req, res) {
res.sendFile(__dirname + '/vendor/css/style.css');
});
app.get('*/vendor/js/app.js', function (req, res) {
res.sendFile(__dirname + '/vendor/js/style.js');
});
#akram-saouri 's answer was almost exact: I ended up using this configuration:
app.use '*/vendor/js', express.static './node_modules/framework/'
app.use '*/vendor/css', express.static './otherFramework/'
for all the app and it worked like a charm
I'm building my first real Express.js app, and stuck on the routing.
I am enabling static hosting:
app.use("/", express.static("public"));
And then I have a wildcard route:
router.get("/:page", function(req, res) {
// do stuff
});
This route is matching for urls like "/about" and "/contact" - which I want. But it appears that it's also trying to match for "/style.css" and other static asset files - which is unnecessary.
How do I make this wildcard not match for asset files?
One solution I found, is to search for a "." inside the query and then set a flag if it's found:
router.get("/:page", function(req, res) {
if (req.render_view) res.render("index");
});
router.param("page", function(req, res, next, page) {
// if request is not an asset file
if (page.indexOf(".") == -1) {
// do stuff
// set a flag
req.render_view = true;
}
next();
});
But I would like to find a cleaner solution, possibly using a regular expression in the router.get?
if I understand what you want to do ,you should just do something like :
app.js
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/static'));
app.use('/:page',function(){}..)
this configuration works when ur public and static folder is relative to app.js, when browser request for static file , first server will look at public folder , if file is no there will continue to static folder and finally to /:page