I want to create a login and registration page for a web application. I have been using this tutorial:
https://thinkster.io/mean-stack-tutorial
However, I want to modify it so everything is not in the same index.ejs file (I do not just want to use "include") but rather on a separate page entirely. In order to do this, I created a register-login.ejs file and a register-login.js file in addition to the index.js file. In my "register-login.js" file I added:
`router.get('/register-login', function(req, res, next) {
res.render('register-login');
});
`
Then in my app.js file I added:
var routes = require('./routes/register-login');app.use('/register-login', routes);
Unfortunately, this attempt results in a 404 Error. How do I properly separate the provided code in the above tutorial into two separate pages: index.js and register-login.js, index.ejs and register-login.ejs and connect them properly?
register extra routes on the router.
var app = express();
var router = express.Router();
router.get('/register', function(req, res, next) {
res.render('./views/register');
});
router.get('/login', function(req, res, next) {
res.render('./views/login');
});
then use them all with app.use('/', router);or app.use(require('./routes/user')); if you export the router and require it
Related
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
Introduction
I have built some back end functionality in Node (First time using Node). Problem is that the whole thing was built in one page (index.js) so now im following a few basic tutorials and setting out express router middleware and now trying to follow a modular MVC approach,
This code is simple but brakes when I separate into two pages Server.js and config.js. I know its a simple problem but i cant spot it. can someone help spot the problem and maybe improve the structure ?
Problem
I go to http://localhost:8080/about or a different route and I get
Cannot GET /about
rather than the correct print out.
back-end/server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
// get an instance of router
var router = express.Router();
// START THE SERVER
// ==============================================
app.listen(port);
console.log('Server has started!! ' + port);
back-end/config.js
router.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
router.get('/', function(req, res) {
res.send('im the home page!');
});
// sample route with a route the way we're used to seeing it
router.get('/sample', function(req, res) {
res.send('this is a sample!');
});
router.get('/about', function(req, res) {
res.send('im the about page!');
});
app.route('/login')
.get(function(req, res) {
res.send('this is the login form');
})
.post(function(req, res) {
console.log('processing'); // shows on console when post is made
res.send('processing the login form!'); // output on postman
});
app.use('/', router);
As #SLaks said in his comment, you need to import (require) your backend/config.js file. But it's not as simple as that...
In node, variables are scoped to the file in which they appear, so if you simply add require('./config') to your server.js file, that's not going to work either, because the router variable in config.js is local to that file - it's not going to know about the router variable in server.js.
The solution to this is to have the config.js file export a function which the server.js file can use to configure stuff. For example
config.js
module.exports = function(router) {
// set up your router here with router.use, etc.
};
server.js
var configure = require('./config');
// after you set up your express router...
configure(router);
// now start listening
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'm new to javascript. I'm trying to make a RESTfull API using Node.js and Express.js
My directory structure is as follows
/server.js
/api/api.js
/api/location/location.js
I want to make the API modular. I want that all the requests (get/post/delete/push) beginning with /api/* to be handled by api.js and whatever routing be required, api.js should route it to proper module.
For example, if someone requests GET /api/location/abc/xyz then api.js will transfer control to location.js which will then transfer to abc.js which will finally transfer to xyz.js stored in directory /api/location/abc/xyz/xyz.js
How can I achieve this?
Code so far:
/server.js
var express = require('express');
var app = express();
var api = require('./api/api.js');
var location = require('./api/location/location.js');
//app.use('/api/location', location); //This works, but I want api.js to handle sub-routes!
app.use('/api', api);
app.get('/', function(req, res){
res.end('successful get/');
});
app.listen(12345);
/api/api.js
module.exports = function(req, res, next) {
res.end('successful get /api');
next();
};
//Add code to handle GET /api/location
/api/location/location.js
module.exports = function(req, res, next){
res.end('from location!');
next();
}
You would use express.Router([options]).
And write it that way:
/api/api.js
var router = require('express').Router();
router.get('/location', require('./api/location') );
module.exports = router;
/api/api/location.js
module.exports = function(req, res, next){
res.end('from location!');
}
And don't call next(); if you ended the response. You only call next() in your callback if you don't handle the response.
I don't know how complex your REST api will be later. But try to to keep the routing in a small number of file. Having a callback for the routing in an own file like /api/api/location.js is most likely not the best idea.
I was having trouble settings up a very basic static file sever using express with Node.js. I set up a simple server.js but cannot see any files when I load the URL localhost:9000 in my web browser.
All I see is a page saying: Cannot get /
var express = require('express');
var app = express();
app.use(function(req, res, next) {
next();
});
app.use(express.static(__dirname));
app.listen(9000);
Simply you're exposing nothing. Do you have, for example, an index.html file? Try this:
app.get("/", function(req, res) {
res.sendfile("index.html");
});
Did you go through the NodeSchool workshoppers? They have step-by-step examples that cover this and more.
Here is the workshop for Express.
Here is my solution for the 'static' question in the workshop.
var express = require('express')
var app = express()
app.use(express.static(process.argv[3]||path.join(__dirname, 'public')));
app.use(require('stylus').middleware(__dirname + '/public'));
app.post('/form', function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end()
})
app.listen(process.argv[2])
Express does not create a directory listing. Even thought it does not list the files in the directory, it does serve them up when hitting them in the web browser.
Point the browser to the actual file:
http://localhost:9000/public/test.html
Originally I found this confusing because I had expected the express server to list directories; when seeing "something"... a page that said "Cannot get /" I assumed that page would normally have a list of files.