I need help with my code, when i use my app in local, everything works perfect. But when i run in server, the app show me this error. Try sending me a message from the form in this link https://silvioli-cv.herokuapp.com/contacto
I don't know what is wrong.
This is my app.js
require('dotenv').config();
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
nodemailer = require('nodemailer'),
flash = require('connect-flash');
// APP CONFIG
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.use(express.static('public'));
// FLASH
app.use(
require('express-session')({
secret: 'Nana es la perra mas bella del mundo',
resave: false,
saveUninitialized: false
})
);
app.use(flash());
app.use(function(req, res, next) {
res.locals.message = req.flash('success');
next();
});
// RUTAS
app.get('/', function(req, res) {
res.render('perfil');
});
app.get('/contacto', function(req, res) {
res.render('contacto');
});
// NODEMAILER CONFIG
app.post('/contacto', function(req, res) {
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: process.env.EMAIL_USERNAME,
clientId: process.env.GMAIL_OAUTH_CLIENT_ID,
clientSecret: process.env.GMAIL_OAUTH_CLIENT_SECRET,
refreshToken: process.env.GMAIL_OAUTH_REFRESH_TOKEN,
accessToken: process.env.GMAIL_OAUTH_ACCESS_TOKEN,
expires: Number.parseInt(process.env.GMAIL_OAUTH_TOKEN_EXPIRE, 10)
}
});
var mailOptions = {
from: req.body.nombre + '<' + req.body.email + '>',
to: process.env.EMAIL_RECIEVER,
subject: req.body.asunto,
html: `
<div>
<p>${req.body.nombre}</p>
<p>${req.body.email}</p>
<p>${req.body.asunto}</p>
<p>${req.body.mensaje}</p>
</div>
`
};
transporter.sendMail(mailOptions, function(err, info) {
if (err) {
console.log(err);
res.send(500, err.message);
} else {
console.log('Email sent');
req.flash('success', 'Su mensaje ha sido enviado con éxito. Muchas gracias.');
res.redirect('/contacto');
}
});
});
// SERVIDOR
// app.listen(3000, function(req, res) {
// console.log('Conectado');
// });
app.listen(process.env.PORT, process.env.IP);
And this is my form contact
<%- include("partials/header") %>
<header class="card-header">
<h2>Contacto</h2>
</header>
<% if(message && message.length > 0){ %>
<div class="container">
<div class="alert alert-success col-md-8" role="alert">
<%= message %>
</div>
</div>
<% } %>
<div class="container mt-4">
<div class="row">
<div class="col-md-12">
<h2>Envíame un correo</h2>
</div>
<div class="col-md-8">
<form action="/contacto" method="POST" style="width: 100%;">
<div class="form-group">
<label for="nombre">Nombre (requerido)</label>
<input type="text" class="form-control" id="nombre" name="nombre" required>
</div>
<div class="form-group">
<label for="email">Email (requerido)</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="form-group">
<label for="asunto">Asunto</label>
<input type="text" class="form-control" id="asunto" name="asunto">
</div>
<div class="form-group">
<label for="mensaje">Su mensaje</label>
<textarea class="form-control" name="mensaje" id="mensaje" rows="4"></textarea>
</div>
<button class="btn btn-lg btn-primary">Enviar mensaje</button>
</form>
</div>
</div>
</div>
<%- include("partials/footer") %>
Related
I have the code below for a login system with nodejs express and mySQL. The registration and the login services work, but the logout doesn't. Also, how can I restrict my pages from a normal user, in order only an admin can access them. File structure:
Here is the code:
app.js
onst path = require('path');
const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const dotenv = require('dotenv');
const cookieParser = require('cookie-parser');
dotenv.config({ path: './.env' });
var flash = require('express-flash');
var session = require("express-session");
const app = express();
// DB connection
const connection = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
connection.connect(function(error) {
if (!!error) console.log(error);
else console.log('CONGRATS! Database Connected! (app)');
});
//set views file
app.set('views', path.join(__dirname, 'views'));
//set public file
app.use(express.static(__dirname + '/public'));
//set view engine
app.set('view engine', 'ejs');
app.use(express.json());
app.use(express.urlencoded({ extended: false })); //instead of false
const routes = require('./server/routes/index');
app.use(session({
cookie: { maxAge: 60000 },
store: new session.MemoryStore,
saveUninitialized: true,
resave: true,
secret: 'mysecret'
}))
app.use(flash());
// Defining Routes
app.use('/', routes);
app.use('/auth', require('./server/routes/auth'));
// Server Listening
app.listen(3000, () => {
console.log('Server is running at port 3000');
});
routes/auth.js
const express = require('express');
const authController = require('../controllers/auth');
const auth_router = express.Router();
auth_router.post('/register', authController.register)
auth_router.post('/login', authController.login);
module.exports = auth_router;
routes/index.js
var express = require('express');
const jwt = require('jsonwebtoken');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
console.log(req.session);
console.log(req.headers.cookie);
res.render('home', {
title: 'Express',
loggedIn: req.headers.cookie
});
});
router.get('/register', (req, res) => {
res.render('register');
});
router.get('/login', (req, res) => {
res.render('login');
});
router.get('/logout', function(req, res) {
req.session.destroy();
res.redirect('/');
})
controllers/auth.js
const mysql = require("mysql");
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
var flash = require('express-flash');
const db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
exports.login = async(req, res) => {
try {
const { username, password } = req.body;
if (!username || !password) {
req.flash('danger', 'Please provide username and password!');
return res.status(400).render('login');
}
db.query('SELECT * FROM users WHERE username = ?', [username], async(error, results) => {
console.log(results);
if (!results || !(await bcrypt.compare(password, results[0].password))) {
req.flash('danger', 'Username or password is incorrect!');
res.status(401).render('login')
} else {
const id = results[0].user_id;
const token = jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN
});
console.log("The token is: " + token);
const cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
),
httpOnly: true
}
res.cookie('jwt', token, cookieOptions);
req.flash('success', 'You logged in successfully');
res.status(200).redirect("/");
}
})
} catch (error) {
console.log(error);
}
}
exports.register = (req, res) => {
console.log(req.body);
const { username, password, passwordConfirm } = req.body;
db.query('SELECT username FROM users WHERE username = ?', [username], async(error, results) => {
if (error) {
console.log(error);
}
if (results.length > 0) {
req.flash('danger', 'That username is already in use!');
return res.render('register');
} else if (password !== passwordConfirm) {
req.flash('danger', 'Passwords do not match!');
return res.render('register');
}
let hashedPassword = await bcrypt.hash(password, 8);
console.log(hashedPassword);
db.query('INSERT INTO users SET ?', { username: username, password: hashedPassword }, (error, results) => {
if (error) {
console.log(error);
} else {
console.log(results);
req.flash('success', 'User registered!');
return res.render('register');
}
})
});
}
views/register.ejs
<!--Navbar Section-->
<%- include('./partials/header'); %>
<!--End Navbar Section-->
<br>
<% if (messages.danger) { %>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<%- messages.danger %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% } %>
<% if (messages.success) { %>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<%- messages.success %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% } %>
<div class="container mt-4">
<div class="card">
<div class="card-header">
Register Form
</div>
<div class="card-body">
<form action="/auth/register" method="POST">
<div class="form-group">
<label for="username">Userame: </label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="form-group">
<label for="passwordConfirm">Confirm Password: </label>
<input type="password" class="form-control" id="passwordConfirm" name="passwordConfirm">
</div>
<button type="submit" class="btn btn-primary">Register User</button>
</form>
</div>
</div>
</div>
views/login.ejs
<!--Navbar Section-->
<%- include('./partials/header'); %>
<!--End Navbar Section-->
<br>
<% if (messages.danger) { %>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<%- messages.danger %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% } %>
<div class="container mt-4">
<div class="card">
<div class="card-header">
Login Form
</div>
<div class="card-body">
<form action="/auth/login" method="POST">
<div class="form-group">
<label for="username">Username: </label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
views/partial/header.ejs
<div class="navbar-collapse collapse w-100 order-3 dual-collapse2">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<!-- <a class="nav-link" href="#" onclick="document.getElementById('id02').style.display='block'">Sign up</a> -->
<a class="nav-link" href="/register">Register</a>
</li>
<li class="nav-item">
<!-- <a class="nav-link" href="#" onclick="document.getElementById('id01').style.display='block'">Login</a> -->
<a class="nav-link" href="/login">Login</a>
</li>
<li class="nav-item">
<!-- <a class="nav-link" href="#" onclick="document.getElementById('id02').style.display='block'">Sign up</a> -->
<a class="nav-link" href="/logout">Logout</a>
</li>
</ul>
</div>
Use middleware to restrict user to access any page without logging in and
I can't seem to find any reason why logout wont work, if you can give the git repo link then I can help you for sure
I'm getting an error when trying to send mail from my website I followed a tutorial on youtube.
Error occurs in index.js which is not even on my server at result.id:
callback(null, { ...result, messageId: result.id });
} catch (error) {
callback(error);
}
};
Here is some of my code server.js:
// email, subject, text
app.post('/email', (req, res) => {
const { subject, email, text } = req.body;
log('Data: ', req.body);
sendMail(email, subject, text, function(err, data) {
if (err) {
log('ERROR: ', err);
return res.status(500).json({ message: err.message || 'Internal Error' });
}
log('Email sent!!!');
return res.json({ message: 'Email sent!!!!!' });
});
});
// Render home page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
// Error page
app.get('/error', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'error.html'));
});
// Email sent page
app.get('/email/sent', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'emailMessage.html'));
});
// Start server
app.get('/',(req, res) =>{
res.sendFile(path.join(__dirname, 'views', 'contact.html'));
});
Here is contact.html:
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="subject" placeholder="Subject" /> <br />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email" /> <br />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea name="text" class="form-control" id="text" cols="30" rows="10"></textarea> <br />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="submit" value="Send Message" class="btn btn-primary"
</div>
Please help in anyway you can this is the last step of the website as you can see it was done in node.js. I searched previous answers and was not able to find one that matched what I'm going through. I can't change the index.js file because it's not on my server.
I am making RESTful BlogApp and PUT method is not working.I only get error saying Cannot PUT /blogs/:id. I don't see what could go wrong. Everything looks fine to me. Please let me know if you find a problem. I know this might be a bad post but it is one of my first posts. Here is what i coded:
<form action="/blogs/<%= blog._id %>?_method=PUT" method="POST" class="ui
form">
<div class="field">
<label for="blog[tittle]">Tittle</label>
<input name="blog[tittle]" type="text" value="<%=
blog.tittle %>">
</div>
<div class="field">
<label for="blog[image]">Image URL</label>
<input name="blog[image]" type="text" value="<%= blog.image
%>">
</div>
<div class="field">
<label for="blog[body]">Content</label>
<textarea name="blog[body]"><%= blog.body %></textarea>
</div>
<button type="submit" class="ui blue button">Save</button>
</form>
const express = require('express');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
const mongoosePassword = 'bm9kZS1yZXN0LWJsb2c=';
mongoose.connect('mongodb://mesopotamija9:' + mongoosePassword + '#node-
rest-blog-shard-00-00-xb2tn.mongodb.net:27017,node-rest-blog-shard-00-01-
xb2tn.mongodb.net:27017,node-rest-blog-shard-00-02-
xb2tn.mongodb.net:27017/test?ssl=true&replicaSet=node-rest-blog-shard-
0&authSource=admin&retryWrites=true', {useNewUrlParser: true});
app.set('view engine', 'ejs')
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
app.put('blogs/:id', function(req, res){
Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err,
updatedBlog){
if (err) {
res.redirect('/blogs');
console.log(err);
} else {
res.redirect('/blogs/' + req.params.id);
console.log(updatedBlog);
}
});
});
I am learning Node.js from a book "Web Development with Nodejs and MongoDB" and is Stuck at a point where I have to upload a Image using Multer.
The Code goes like this :-
Below is My Configure.js file :
var path = require('path'),
routes = require('./routes'),
exphbs = require('express-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
multer = require('multer');
moment = require('moment');
var upload = multer({ dest: './public/upload/temp' });
module.exports = function(app) {
app.use(morgan('dev'));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes(app);
app.post('/public/upload/temp', upload.single('img'), function(req, res) {
//var form_description = req.body.description;
console.log(req.file.name);
// insert operations into database get placed here
res.redirect('/');
});
app.use('/public/', express.static(path.join(__dirname,
'../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
app.engine('handlebars', exphbs.create({
defaultLayout: 'main',
layoutsDir: app.get('views') + '/layouts',
partialsDir: app.get('views') + '/partials',
helpers: {
timeago: function(timestamp) {
return moment(timestamp).startOf('minute').fromNow();
}
}
}).engine);
return app;
};
Below is the Handlebar file or (HTML) file :-
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Upload an Image
</h3>
</div>
<form method="post" action="/images" enctype="multipart/formdata">
<div class="panel-body form-horizontal">
<div class="form-group col-md-12">
<label class="col-sm-2 control-label" for="file">Browse:</label>
<div class="col-md-10">
<input class="form-control" type="file" name="file" id="file">
</div>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label" for="title">Title:</label>
<div class="col-md-10">
<input class="form-control" type="text" name="title">
</div>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label" for="description">Description
</label>
<div class="col-md-10">
<textarea class="form-control" name="description" rows="2"></textarea>
</div>
</div>
<div class="form-group col-md-12">
<div class="col-md-12 text-right">
<button type="submit" id="login-btn"
class="btn btn-success" type="button">
<i class="fa fa-cloud-upload ">
</i> Upload Image</button>
</div>
</div>
</div>
</form>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
</h3>
</div>
<div class="panel-body">
{{#each images}}
<div class="col-md-4 text-center" style="padding-bottom:1em;">
<a href="/images/{{ uniqueId }}">
<img src="/public/upload/{{filename}}" alt="{{title}}" style="width:
175px; height: 175px;" class="imgthumbnail">
</a></div>
{{/each}}
</div>
</div>
Below is the image.js Controller File :-
var fs = require('fs');
var path = require('path');
module.exports = {
index: function(req, res) {
var viewModel = {
image: {
uniqueId: 1,
title: 'Sample Image 1',
description: 'This is a sample.',
filename: 'sample1.jpg',
views: 0,
likes: 0,
timestamp: Date.now
},
comments: [{
image_id: 1,
email: 'test#testing.com',
name: 'Test Tester',
gravatar: 'http://lorempixel.com/75/75/animals/1',
comment: 'This is a test comment...',
timestamp: Date.now
}, {
image_id: 1,
email: 'test#testing.com',
name: 'Test Tester',
gravatar: 'http://lorempixel.com/75/75/animals/2',
comment: 'Another followup comment!',
timestamp: Date.now
}]
};
res.render('image.handlebars', viewModel);
},
create: function(req, res) {
var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
imgUrl = '';
for (var i = 0; i < 6; i += 1) {
imgUrl += possible.charAt(Math.floor(Math.random() *
possible.length));
}
var tempPath = req.file.path,
ext = path.extname(req.file.name).toLowerCase(),
targetPath = path.resolve('./public/upload/' + imgUrl + ext);
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext ===
'.gif') {
fs.rename(tempPath, targetPath, function(err) {
if (err) throw err;
res.redirect('/images/' + imgUrl);
});
} else {
fs.unlink(tempPath, function() {
if (err) throw err;
res.json(500, { error: 'Only image files are allowed.' });
});
}
},
like: function(req, res) {
res.send('The image:like POST controller');
},
comment: function(req, res) {
res.send('The image:comment POST controller');
}
};
When run the server and visit the website on localhost and try to upload a image by clicking on Upload Image button this error comes :-
Cannot read property 'path' of undefined
at create (G:\Docs\Node.js\Project\imgploader.io\controllers\image.js:40:32)
at Layer.handle [as handle_request] (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\layer.js:95:5)
at next (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\layer.js:95:5)
at G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:281:22
at Function.process_params (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:335:12)
at next (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:275:10)
at Function.handle (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:174:3)
at router (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:47:12)
What is the Problem ? I have tried everything available on the Internet but still the same !
Please Help
Maybe because you have used ( ; ) at the end of error handler declaration
errorHandler = require('errorhandler');
also in your HTML name attribute should be img as you have used it multer.
Im trying to build a node.js application and when I try to do a post request on a register or login method, it seems to keep loading and not do anything. I get the following error in my web broswer - "localhost didn’t send any data" . Here is the way I have my code setup:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
passport = require("passport"),
flash = require("connect-flash"),
LocalStrategy = require("passport-local"),
methodOverride = require("method-override"),
User = require("./models/user");
mongoose.connect("mongod://localhost/supportApp_v1");
app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
app.use(require("express-session")({
secret: "luck",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function(req,res,next){
res.locals.currentUser = req.user;
res.locals.error = req.flash("error");
res.locals.success = req.flash("success");
next();
});
app.get("/", function(req, res){
res.render("landing");
});
app.get("/register", function(req, res){
res.render("register");
});
app.post("/register", function(req, res){
var newUser = new User({username: req.body.username});
User.register(newUser, req.body.password, function(err, user){
if (err) {
return res.render("register", {"error": err.message});
} else {
passport.authenticate("local")(req, res, function(){
req.flash("success", "Welcome " + user.username);
res.redirect("/");
});
}
});
});
app.get("/login", function(req, res){
res.render("login");
});
app.post("/login", passport.authenticate("local",
{
successRedirect: "/",
failureRedirect: "/login",
}), function (req, res){
});
app.listen(process.env.PORT || 3000, process.env.IP, function(){
console.log("Server has started");
});
The model that Im using:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
age: Number
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
and a registration form:
<div class="container" id="regContainer">
<h1>Register</h1>
<hr>
<form action="/register" method="POST">
<div class="form-group row">
<label for="regUser" class="col-sm-2 col-form-label">Username:
</label>
<div class="col-sm-10">
<input id="regUser" type="text" name="username" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="regUser" class="col-sm-2 col-form-label">Email:</label>
<div class="col-sm-10">
<input id="regUser" type="text" name="email" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="regPass" class="col-sm-2 col-form-label">Password:</label>
<div class="col-sm-10">
<input id="regUser" type="password" name="password" placeholder="Password">
</div>
</div>
<div class="form-group row">
<label for="regPass" class="col-sm-2 col-form-label">Age:</label>
<div class="col-sm-10">
<input id="regUser" type="number" name="age" placeholder="Age">
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-10">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</div>
Connection via Mongoose is
mongoose.connect('mongodb://localhost/myapp');
Yours is missing a d. #MariaInesParnisari also suspected connection problem. I also notice that your register.html is missing a dew tags near the end such as </form>(may be due to incomplete copy-and-paste). I also wonder where you place the .html files, as you did not set the path for 'views' , for example
app.set('views', path.join(__dirname, '/views'));
Perhaps you are using the default?