I'm a big newb at node.js so please don't start bashing me just yet. I'm using the express framework and i am trying to build a simple application to display as html.
Here's the basic app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', routes);
//app.use('/users', users);
app.use('/registration', require('./routes/registration'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(3000, function () {
console.log("Poslusam na portu 3000!");
});
module.exports = app;
Here's the regisration.js code i'm trying to display
var express = require('express');
var router = express.Router();
var db = require('../node_modules/nyModule/db.js');
var app = express();
var users = db.getUsers();
router.get('/', function (req, res) {
res.render('registration');
});
router.post('/', function (req, res) {
var registration = JSON.stringify(req.body);
console.log(registration);
var o = JSON.parse(registration);
console.log("Login: " + o.email);
baza.addRegistration(o);
res.redirect('/');
});
module.exports = router;
and here's the registration.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h2>App</h2>
<h3>Registration/h3>
<form method="post">
<label>Name: </label><br />
<input type="text" name="name" id="name" /><br /><br />
<label>LastName: </label><br />
<input type="text" name="lname" id="lname" /><br /><br />
<label>Elektronski naslov:</label><br />
<input type="text" name="email" id="email" /><br /><br />
<label>Username: </label><br>
<input type="text" name="username" id="username" /><br> <br>
<label>Password</label><br>
<input type="password" name="password" id="password" /><br>
<input type="submit" value="Register" />
</form>
</body>
</html>
This is the result that i get on localhost:3000
Please help me
update
Line: 20
You should set view engine as html file.
Insert this code into app.js file.
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
Related
edit:guys I'm genually new to all of this. here's the html form I used. should i update this question with something else?
<form action="/pesquisar" method="post">
<input type="text" id="cO">
<input type="text" id="cD">
<input type="submit">
</form>
I'm currently trying to design a simple browser app utilizing express. console.log(req.body) comes back {} and i cant find the solution, been here for the best part of the day lol
Here's my app
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res){
console.log(req.body);
res.render('index', {
infoVoos: 'acesso_inicial'
});
});
app.post('/pesquisar', function(req,res){
console.log("");
console.log("");
console.log(req.body);
res.send('ok');
});
app.listen(3000);
console.log('############');
console.log('Server on');
console.log('');
module.exports = app;
I changed the parameter of the input tag from "id" to "name" and it's working fine now.
original
<form action="/pesquisar" method="post">
<input type="text" id="cO">
<input type="text" id="cD">
<input type="submit">
</form>
new
<form action="/pesquisar" method="post">
<input type="text" name="cO">
<input type="text" name="cD">
<input type="submit">
</form>
thankx guys
I am using the express framework with EJS as the view engine. I have some basic routes ('/' & '/users') in the application. I also have a form in my EJS page which I'm using the users to login. Here I have form with action="/login" and method="POST". And I have created a handler function app.post in the app.js to check credentials and redirect to users page.
But when I click submit button of the page express app saying that "/login" not found. Below is the directory structure of the entire app.
menu.ejs:
<form method="POST" action="/login">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" name="login" class="login loginmodal-submit" value="Login">
</form>
And the app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var path = require('path');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
//express session
app.use(session({
secret:'secret_key',
resave:true,
saveUninitialized:true
}));
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(bodyParser.json());
mysql
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'secret_pw',
database:'my_db'
});
//login authentication
app.post('/login', function(req,res){
var username = req.body.username;
var password = req.body.password;
if(username && password){
connection.query('SELECT username,password FROM logindetails WHERE username = ? AND password = ?',[username,password], function(error,results,fields){
if(results.length > 0){
req.session.loggedin = true;
req.session.username = username;
res.redirect('/users');
} else{
res.send('Incorrect username and password');
}
res.end();
});
}
else{
res.send('Please enter username and password');
res.end();
}
});
module.exports = app;
And the login route is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { page:'home', menuId:'home' });
});
module.exports = router;
Omit this code from app.js
app.post('/login', function(req,res){
/....../
});
Then add this to login-router
router.post('/', function(req, res) {
/......../
});
Because your app reach this block below before executing app.post
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
Move the following block below app.post.
Also, you should initialise bodyParser and session before initialising routes.
I am getting odd behavior for the route modules in this simple express app.
The root page '/' works but I am getting a 'not found' error for '/login'. But it works when I do app.get('/login', auth), instead of app.use('/login', auth). Any help is appreciated!
app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000
const path = require("path");
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const auth = require('./routes/auth');
const index = require('./routes/index');
mongoose.connect("mongodb://localhost/dev");
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use('/login', auth);
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error', { res : res });
});
app.listen(port);
./routes/index
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('index');
});
module.exports = router;
./routes/auth
var express = require('express');
var router = express.Router();
router.get('/login', function (req, res, next) {
res.send('Hello world');
});
router.post('/login', function (req, res, next) {
res.send('Goodbye world');
});
module.exports = router;
./views/index.ejs
<h1>Welcome To Our App</h1>
Login
Signup
./views/login.ejs
<h1>Login</h1>
<form action="/login" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
In /routes/auth.js do router.get('/') instead of router.get('/login').
Otherwise, you would have to call localhost/login/login.
I've tried to get csurf to work but seem to have stumbled upon something. The code so far looks like this:
index.ejs
<form method="post" action="/">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
.
.
</form>
Where you insert password and username in the form.
app.js
var express = require('express');
var helmet = require('helmet');
var csrf = require('csurf');
var path = require('path');
var favicon = require('serve-favicon');
var flash = require('connect-flash');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
var profile = require('./routes/profile');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
//Security shyts
app.use(helmet());
app.use(helmet.xssFilter({ setOnOldIE: true }));
app.use(helmet.frameguard('deny'));
app.use(helmet.hsts({maxAge: 7776000000, includeSubdomains: true}));
app.use(helmet.hidePoweredBy());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.noCache());
// rest of USE
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'anystringoftext', saveUninitialized: true, resave: true, httpOnly: true, secure: true}));
app.use(csrf()); // Security, has to be after cookie and session.
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/profile', profile);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.locals.csrftoken = req.csrfToken();
next();
})
//app.use(function(req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
//});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Where I've put csrf after session and cookie parser.
index.js
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'some title',message: '' });
});
router.post('/',function(req,res){
// Where I have a bunch of mysql queries to check passwords and usernames where as if they succeed they get:
res.redirect('profile');
// Else:
res.redirect('/');
});
What I get after submiting the form, no matter if I insert the correct username and password or not I still get the same error:
invalid csrf token
403
ForbiddenError: invalid csrf token
Also I want add that I've been working with node for about 2 weeks, so there is still alot I need to learn probably.
{{csrfToken}} isn't an EJS construction, so it's not expanded at all and is probably sent literally to your server.
This should work better:
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
The middleware is setting csrftoken though, with lowercase 't', where the template expects an uppercase 'T':
res.locals.csrftoken = req.csrfToken(); // change to `res.locals.csrfToken`
You also generate two different tokens, which is probably not what you want. Store the token in a variable and reuse that:
app.use(function (req, res, next) {
var token = req.csrfToken();
res.cookie('XSRF-TOKEN', token);
res.locals.csrfToken = token;
next();
});
And lastly, you probably have to move your middleware to before the route declarations, otherwise it won't be called:
app.use(function (req, res, next) {
var token = req.csrfToken();
res.cookie('XSRF-TOKEN', token);
res.locals.csrfToken = token;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/profile', profile);
My Express version is 6.14.4. The most important matter is you have to maintain the order of the line.
App.js
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var bodyParser = require('body-parser');
//order of bellow lins is very important
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(csrf({ cookie: true }))
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/user/signup', function(req, res, next){
console.log("csruf: "+req.csrfToken());
res.render('user/signup', { csrfToken: req.csrfToken() });
});
router.post('/postuser', function(req, res, next){
//res.render('/');
res.redirect('/');
});
view file
<form action="/postuser" method="POST">
<div class="form-group">
<label for="email"> E-Mail</label>
<input type="text" id="email" name="email" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" class="form-control">
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit" class="btn btn-primary">Sign Up</button>
</form>
Using nodeJs,ExpressJS(~4)
This is my structure:
controllers/searchController.js
public/javascripts/search.js (js client code that will run on browser)
public/search.html
server.js
app.js
searchController.js:
var express = require('express');
var router = express.Router();
var esService = require('../services/esService');
var Q = require('q');
var html_dir = './public/';
router.get("/home", function (req, res) {
res.sendfile(html_dir + 'search.html');
})
router.get("/search", function (req, res) {
...
})
module.exports = router;
app.js:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var searchController = require('./controllers/searchController');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(__dirname, '/public'));
app.use('/', searchController);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
search.html:
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
........
<div id="tfheader">
<form id="tfnewsearch" method="get" onsubmit="return handleClick()">
<input id="myinput" type="text" class="tftextinput" name="q" size="21" maxlength="120">
<input type="submit" value="search" class="tfbutton">
</form>
<div class="tfclear"></div>
</div>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="javascripts/prettyprint.js"></script>
<script src="javascripts/search.js"></script>
...
</body>
</html>
and this is search.js:
function handleClick() {
var inputParam = document.querySelector("#myinput").value;
$.get('search?termToSearch=' + inputParam, function (responseText) {
console.log(responseText);
$("#resultlist").empty().append(prettyPrint(responseText));
});
return false;
}
Now when I acesss to: http://localhost:3000/home I am getting the folloing error on the browser:
Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/javascripts/search.js
Request Method:GET
Status Code:404 Not Found
Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/javascripts/prettyprint.js
Request Method:GET
Status Code:404 Not Found
Any idea why?
You should change
app.use(express.static(__dirname, '/public'));
to:
app.use(express.static(__dirname + '/public'));
But if you really want to fix this problem it's better to use an prefix for static file like this:
app.use('/public', express.static(__dirname + '/public'));
and then load your Javascript files in this way:
<script src="public/javascripts/prettyprint.js"></script>
<script src="public/javascripts/search.js"></script>