Why do my POST requests keep infinitely loading? - javascript

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?

Related

What is causing the type error in my code?

I am trying to console.log the input in this sign up form but every time i fill the details and the submit the form then it shows the following error
TypeError: Cannot read properties of undefined (reading 'fName')
Kindly let me know the error in my code.
<form action="/" method="POST">
<img class="mb-4" src="images/mail.jpg" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Signup the Newsletter</h1>
<div class="form-floating">
<input type="text" name="fName" class="form-control top" placeholder="First Name">
</div>
<div class="form-floating">
<input type="text" name="lName" class="form-control middle" placeholder="Last Name">
</div>
<div class="form-floating">
<input type="email" name="email" class="form-control bottom" placeholder="name#example.com">
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">Follow me</p>
</form>
// const https = require("https");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(res, req){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
app.listen(3000, function() {
console.log("Server is running on Port 3000");
}); ```
I found these errors in your code, check them and it will work fine.
app.use("/public", express.static(path.join(__dirname, 'public'))); // use this for defining your public folder (and don't forget to import path module above).
app.post("/", function(req, res, next){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
Here as you can see in the callback function we get three parameters first will be the request object, second will be the response object and third is optional next object.
But in your case you are reading it from response object but it should be from request.
Thanks

No recipients defined from server Nodemailer . From local work fine

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") %>

How to fix Cannot PUT /blogs/:id

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);
}
});
});

Why can't I successfully to fetch url from form and thus attribute it to the source(src) of images?

I've having an issue I shouldn't be having with my Node/Express code(s). I can't for the life of me get the image source (src) attribute to work, hence the images added from a form aren't being displayed. It just displays as unknown. I have no idea where I'm going wrong, and have gone through the whole code(s) multiple times, but nothing seems out of place.
The JS code is as follows:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/yelpcamp");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
//Camp Schema
var campgroundSchema = new mongoose.Schema({
name: String,
image: String
});
var Campground = mongoose.model("Campground", campgroundSchema);
app.get("/", function(req, res) {
res.render("landing");
});
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, sites) {
if(err) {
console.log(err);
}
else {
res.render("campgrounds", {
campgrounds:sites
});
}
});
});
app.post("/campgrounds", function(req, res){
//Fetching data from form
var name = req.body.campName;
var url = req.body.imageUrl;
var newCamp = {
name: name,
image: url
};
//New Campground and Save to DB
Campground.create(newCamp, function(err, campground) {
if(err) {
console.log(err);
}
else {
//Redirect to Camp Page
console.log(campground);
res.redirect("/campgrounds");
}
});
});
app.get("/campgrounds/new", function(req, res){
res.render("new");
});
app.listen(4500, function(){
console.log("Yelp Camp Server Started!!!");
});
The following are the relevant EJS codes:
Form EJS
<div class="container">
<form action="/campgrounds" method="POST">
<label for="campName">Name</label>
<input type="text" id="campName" name="campName" placeholder="Add Campground Name">
<label for="campImage">Image</label>
<input type="url" id="campImage" name="imageUrl" placeholder="Add Image Url">
<input type="submit" name="submit" value="Add Campground">
</form>
Go Back
</div>
Add Image EJS
<div class="container">
<h1 style="margin-top: 8%;">Campgrounds Presentation</h1>
<div class="row">
<% campgrounds.forEach(function(campground) { %>
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="thumbnail">
<img src="<%= campground.image %>">
<h3 class=text-center><%= campground.name %></h3>
</div>
</div>
<% }); %>
</div>
</div>

Passport JS does not give error but, does not seem to work

I have a basic register and login app. After the user registers, and stores their information into my sequelize model, I redirect the page to the login page. When I try to login with the username and password I just made, it doesn't throw any errors, but the page goes into an endless loading phase where it eventually says The localhost page isnt working localhost didn't send any data'ERR_EMPTY_RESPONSE`
//Routes
var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var router = express.Router();
var db = require('../models');
router.get('/', function(req, res){
res.redirect('/friend-book');
});
router.get('/friend-book', function(req, res){
res.render('home');
});
router.get('/friend-book/profile', function(req, res){
res.render('profile');
});
router.get('/friend-book/login', function(req, res){
res.render('login');
});
router.get('/friend-book/register', function(req, res){
res.render('register');
});
router.post('/friend-book/search/user', function(req, res){
db.users.findAll({
where: {
name: req.body.name
}
}).then(function(data){
var userResults = {
people: data
}
res.render('searchedUser', userResults);
})
});
router.post('/friend-book/register', function(req, res){
console.log(req.body);
var name = req.body.name;
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
var description = req.body.description
req.checkBody('name', 'Must type in name.').notEmpty();
req.checkBody('username', 'Must type in Username.').notEmpty();
req.checkBody('email', 'Must type in email.').notEmpty();
req.checkBody('email', 'Invalid Email').isEmail();
req.checkBody('password', 'Must type in password.').notEmpty();
req.checkBody('password2', 'Passwords do not match.').equals(req.body.password);
req.checkBody('description', 'Must type in something about yourself.').notEmpty();
var errors = req.validationErrors();
//If there are errors, render the errors
if(errors){
res.render('register', {
errors: errors
});
}else{
db.users.create(req.body).then(function(data){
console.log("register data", data);
console.log("poop", data.id);
req.session.user = {
id: data.id,
name: data.name,
username: data.username,
email: data.email,
description: data.description
};
req.flash('success_msg', 'Success! Welcome to Book Face!');
// res.render("profile", req.session.user);
res.redirect('/friend-book/login')
});
}
//***************************************************************************************************
});
passport.use(new LocalStrategy(
function(username, password, done) {
db.users.findOne({
where: {
username: username
}
}, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
db.users.findById(id, function(err, user) {
done(err, user);
});
});
router.post('/friend-book/login',
passport.authenticate('local',
{
successRedirect: '/',
failureRedirect: '/friend-book/login',
failureFlash: true
}),function(req, res){
res.redirect('/friend-book/profile' + req.user.username);
}
);
module.exports = router;
//My model
var bcrypt = require('bcryptjs')
module.exports = function(sequelize, DataTypes){
var users = sequelize.define('users', {
name: DataTypes.STRING,
username: DataTypes.STRING,
password: DataTypes.STRING,
email: DataTypes.STRING,
description: DataTypes.STRING
}, {
hooks: {
beforeCreate: function(user, options){
return new Promise(function(resolve, reject){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {reject(err)}
user.password = hash;
console.log(user.password);
resolve();
});
});
})
}
}
});
return users;
}
//login handlebars
<div class="container">
<form action="/friend-book/login" method="POST" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputUsername" class="sr-only">Username</label>
<input type="text" name="username" id="inputUsername" class="form-control" placeholder="Username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
//Registration handlebars
<div class="container">
<h2 class="form-register-heading">Book Face Registration</h2>
{{#if errors}}
{{#each errors}}
<div class="alert alert-warning">{{msg}}</div>
{{/each}}
{{/if}}
<form action="/friend-book/register" method="POST" class="form-signin">
<div class="form-group">
<label for="inputName" class="sr-only">Name</label>
<input type="text" name="name" id="inputName" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<label for="inputUsername" class="sr-only">Username</label>
<input type="text" name="username" id="inputUsername" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<label for="inputPassword2" class="sr-only">Password</label>
<input type="password" name="password2" id="inputPassword2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<label for="inputEmail" class="sr-only">Email</label>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label for="inputDescription" class="sr-only">Description</label>
<input type="text" name="description" id="inputDescription" class="form-control" placeholder="Type something">
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
</form>
</div> <!-- /container -->
You only handle POST requests to /friend-book/login.
When you use res.redirect('/friend-book/login'), it'll redirect the user using GET method to that URL.
router.get('/friend-book/login', function (req, res) {
res.render('login');
});

Categories

Resources