EJS cannot read variable in html page - javascript

I'm new at backend programming and having diffuculty with using EJS and routes. I'm using a database as well. The problem is , a dynamic js variable cannot displaying in ejs view file. I mean "message" like "the password does not match <%= message %> Can you help me ? These are my codes. I've shortened them as much as i can do. I don't think database files are important for the solution so did not include them. Thanks !
This is my main index.js file :
const express = require("express");
const app = express();
const path = require('path');
const dotenv = require('dotenv') ;
dotenv.config({path:'./.env'})
app.set("view engine", "ejs");
app.use(express.static('public'));
app.use(express.static('node_modules'));
app.use(express.urlencoded({ extended: false })); //false yerine true da koyulabilir.
app.use(express.json());
//Define routes
app.use('/',require('./routes/pages'));
app.use('/auth',require('./routes/auth'));
app.listen(3000, () => {
console.log("Listening on port 3000");
});
This is my auth.js(controllers) file :
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db_kullanici_auth = require("../data/kullanici_auth_db"); //it's a database importing
exports.register = async (req, res) => {
try {
// console.log(req.body) ;
// res.send("Form submitted") ;
// let query = "SELECT email FROM register;"
// const allDB = await (db_kullanici_auth.execute(query));
// const projeler_db = allDB[0];
// console.log(projeler_db);
const { company_name_reg, name_reg, surname_reg, department_name_reg, position_name_reg, password_reg, password_confirm_reg, adres_reg, adres2_reg, zip_reg, sehir_reg, ulke_reg, telefon_kodu_reg, telefon_numarasi_reg, email_reg } = req.body;
await (db_kullanici_auth.execute('SELECT email FROM register WHERE email = ? ', [email_reg], (error, results) => {
if (error) {
console.log(error);
}
if (results.length > 0) {
console.log(results);
return res.render('kayit_ol', {
message: 'Email is already in use'
});
}
else if (password_reg !== password_confirm_reg) {
console.log(results);
return res.render('kayit_ol', {
message: 'Passwords does not match'
});
}
// let hashedPassword = await bcrypt.hash(password_reg,8) ;
// console.log(hashedPassword) ;
}));
} catch (error) {
console.log(error);
}
}
This is my auth.js(routes) file :
const express = require('express') ;
const router = express.Router() ;
const authController = require('../controllers/auth');
router.post("/kayit_ol",authController.register);
module.exports = router ;

Related

Can't get my api to work in Postman, POST returns 404 . its a vue frontend and express backend

I'm following this tutorial and I'm stuck at the end. getting 404's in postman when using POST with this URL http://localhost:5050/api/projects its been 3 days any one know what I'm doing wrong?
server.js
const express = require("express");
const app = express();
const PORT = 5050;
// Connect to the database
require("./src/server/database/connection");
const bodyParser = require("body-parser");
const cors = require("cors");
var corsOptions = {
origin: "http://localhost:5051"
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Code Wire Server." });
});
require("./src/server/routes/routes")(app);
app.listen(PORT, () => {
console.log(`Server is listening at http://localhost:${PORT}`);
});
connection.js
How to connect to the database
const db = require("../model/index.js");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
index.js
const dbConfig = require("../config/db.config.js");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.project = require("./projects_db.js")(mongoose);
module.exports = db;
db.config.js
module.exports = {
url: "mongodb://127.0.0.1:27017/code-wire-db"
}
projects_db.js
A database schema for my project I'm working on
module.exports = mongoose => {
var schema = mongoose.Schema({
project_title: String,
description: String,
} );
schema.method("toJSON", function() {
// eslint-disable-next-line no-unused-vars
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const projectsDB = mongoose.model("projectsDB", schema);
return projectsDB;
projects_controller.js
const db = require("../model/index");
const project = db.project;
// Create and Save a new project
exports.create = (req, res) => {
// Validate request
if (!req.body.title) {
res.status(400).send({ message: "Content can not be empty!" });
return;
}
// Create a project
const Project = new project({
project_title: req.body.project_title,
description: req.body.description
});
// Save project in the database
Project
.save(Project)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Project."
});
});
};
routes.js
module.exports = app => {
const projects = require("../controller/projects_controller.js");
var router = require("express").Router();
// Create a new project
router.post("/", projects.create);
app.use('/api/projects', router);
};
I found the problem.
[![problem][1]][1]
See that return symbol, I found out 4 days later that means there is 2 lines or more. Meaning postman was sending 2 lines instead of one. With no error message
[1]: https://i.stack.imgur.com/VVlha.jpg

Exporting Multiple Objects Stops My HTML Requests from being processed

I have some simple javascript code in three files. There is my server.js, which has
const userRouter = require('./routes/users')
app.use("/",userRouter)
Then there is my middleware users.js with
module.exports = router
and lastly user.js with
module.exports = {
User:User,
validateLogin:validateUserLogin,
validateRegister:validateUserRegister,
}
When my user.js had just the export line module.exports = User my code worked just fine. server.js imports users.js, which imports user.js. But when exporting functions along with my User object, my requests stop working. Why? How can I fix this? I'm using Node.js with express and mongo db. All my HTML requests are in users.js.
The code to my server.js is
const express = require('express');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
//just show server is running
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const PORT = 4000;
app.get("/status", async (req, res) => {
return res.status(400).send("server for GET is running");
});
app.post("/status", async (req, res) => {
return res.status(200).send({
status: "server for POST is running",
message: req.body.message
});
});
app.listen(PORT, function() {
console.log(`server running on port ${PORT}`);
});
const url = "mongodb+srv://Admin:strongpassword#cluster0.tjual.mongodb.net/ConfusedTom?retryWrites=true&w=majority"
mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "ConfusedTom"
}).then(() => {
console.log("connected successfully to server, using database %s\n", mongoose.connection.$dbName);
}).catch(err => {
console.log(err);
});
const userRouter = require('./routes/users')
app.use("/",userRouter)
and here is my users.js
const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();
const ObjectId = mongoose.Types.ObjectId;
const Review = require("../models/review.js")
const TVShow = require("../models/tvshows.js")
const { User, validateLogin, validateRegister} = require("../models/user.js")
router.get("/username", async (req, res) => {
console.log("reached!")
var user = await User.findOne({ username: req.body.username });
if (!user) return res.status(400).send("User doesn't exist.");
return res.status(200).send(user)
});
router.post("/register", async(req,res) => {
const { error } = validateRegister(req.body);
if (error) return res.status(400).send(error.details[0].message);
else user = await User.findOne({ username: req.body.username });
if (user) return res.status(400).send("Username already taken.");
//create new user
user = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
username: req.body.username,
password: req.body.password,
});
user.save();
return res.status(200).send("User registered successfully.");
})
router.post("/login", async (req, res) => {
console.log("reached!")
// validate the request body first
const { error } = validateLogin(req.body);
if (error) return res.status(400).send(error.details[0].message);
//find an existing user
var user = await User.findOne({ username: req.body.username });
if (!user) return res.status(400).send("Username reqired.");
if (user) {
if (user.validatePassword(req.body.password)) {
return res.header.status(200).send("User login successfully");
}
else return res.status(400).send("Password is incorrect");
} else return res.status(400).send("User doesn't exist.");
});
module.exports = router
The problem with your updated import of the stuff from user.js is you're using the wrong names for the functions. You currently have:
const UserStuff = require("../models/user.js")
const User = UserStuff.User;
const validateLogin = UserStuff.validateUserLogin;
const validateregister = UserStuff.validateUserRegister;
but the object you're exporting is:
module.exports = {
User:User,
validateLogin:validateUserLogin,
validateRegister:validateUserRegister,
}
You're using the wrong names of the functions (validateUserLogin instead of validateLogin). The names you use have to match at both ends. So:
const UserStuff = require("../models/user.js")
const User = UserStuff.User;
const validateLogin = UserStuff.validateLogin;
// ^^^^^^^^^^^^^
const validateregister = UserStuff.validateRegister;
// ^^^^^^^^^^^^^^^^
or more concisely:
const { User, validateLogin, validateRegister} = require("../models/user.js")

Fetching csrf token using csurf from function not api route

I created a api route named "/add" that renders a file named "additional-user-info" with crsf token and it works fine
app.js
const express = require("express");
require("dotenv").config();
const mongoose = require("mongoose");
const authRoutes = require("./routes/authRoutes");
const cookieParser = require("cookie-parser");
var csrf = require("csurf");
var csrfProtection = csrf({ cookie: true });
const {
requireAuth,
checkUser,
displayallusers,
deleteUser,
searchuser,
isAdmin,
} = require("./middleware/authMiddleware");
const mongoSantize = require("express-mongo-sanitize");
const xss = require("xss-clean");
const app = express();
// middleware
app.disable("x-powered-by");
app.use(express.static("public"));
app.use(mongoSantize());
app.use(xss());
app.use(express.json());
app.use(cookieParser());
//handling wrong invlid json syntax
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && "body" in err) {
//console.error(err);
return res.status(400).send("Invalid Json formatting"); // Bad request
}
});
// view engine
app.set("view engine", "ejs");
// database connection
const mongoUsername = process.env.MONGO_USERNAME;
const mongoPassword = process.env.MONGO_PASSWORD;
const dbURI =
"mongodb+srv://" +
mongoUsername +
":" +
mongoPassword +
"#boioboi/real-auth?retryWrites=true&w=majority";
mongoose
.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then((result) => app.listen(3000))
.catch((err) => console.log(err));
// routes
app.get("*", checkUser);
app.get("/add", csrfProtection, (req, res) => {
console.log("zeeeeeeeee");
console.log(req.csrfToken());
res.render("additional-user-info", { csrfToken: req.csrfToken() });
});
app.get("/", (req, res) => res.render("home"));
app.get("/smoothies", requireAuth, (req, res) => res.render("smoothies"));
app.use(authRoutes);
Website has a functionality that if a user creates an account or logins into his account and has certian database fields empty website would render same "additional-user-info" page to get his info
This is a function that checks if a user is valid or not and renders "additional-user-info" page if certain fields are empty
authMiddleware
const checkUser = (req, res, next) => {
const token = req.cookies.jwt;
if (token) {
jwt.verify(token, jwt_secret, async (err, decodedtoken) => {
if (err) {
console.log(err.message);
res.locals.user = null;
next();
} else {
console.log(decodedtoken);
let user = await User.findById(decodedtoken.id);
res.locals.user = user;
if (
(user.additionalinfo.fullname == "") |
(user.additionalinfo.address == "") |
(user.additionalinfo.city == "") |
(user.additionalinfo.district == "") |
(user.additionalinfo.propertytype == "") |
(user.additionalinfo.adharcard == "") |
(user.additionalinfo.pancard == "")
) {
return res.render("additional-user-info"); //crsf-token is not defined error here
}
next();
}
});
} else {
res.locals.user = null;
next();
}
};
But when it renders "additional-user-info" page from checkUser() function it gives error saying "csrfToken is not defined". How should i fix this issue?

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Why does the bodyParser not working?

This is my index.js file and i think i have placed the routes after installing bodyParser but still getting the syntax error.
const express = require('express'); //Framework to build server side application
const morgan = require('morgan'); //Logging the nodejs requests
const bodyParser = require('body-parser'); //To get the JSON data
const urls = require('./db/urls');
const app = express();
app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(express.static('./public')); //If a request comes with '/' check if file is in there if it is then serve it up.
// app.get('/', (req, res) => {
// res.send('Hello, World !!');
// });
app.post('/api/shorty', async (req, res) => {
console.log(req.body);
try {
const url = await urls.create(req.body); //Passing the body data which is JSON to create function
res.json(url);
} catch (error) {
res.status(500);
res.json(error)
}
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
This is the urls.js file,I am not getting where have i messed up to make Syntax.JSON error in this file.
const db = require('./connection');
const Joi = require('joi');//Schema validation
const urls = db.get('urls');
const schema = Joi.object().keys({
name : Joi.string().token().min(1).max(100).required(),
url : Joi.string().uri({
scheme: [
/https?/ //get http 's' is optional
]
}).required()
}).with('name','url');
//almostShorty = {
// name = ,
// url =
// }
function create(almostShorty){
const result = Joi.validate(almostShorty, schema);
if(result.error === null){
return urls.insert(almostShorty);//Inserting the object in the Data Base.
}else{
return Promise.reject(result.error);
}
};
module.exports = {create};//Exporting the create function.

Redirect after Post method , expressjs

I'm learing ExpressJS, and so far I did the user registration part but when I want to redirect to the home page after finishing the registration, it's not
showing the json after clicking on Submit button. May I know how I could do it.
Database
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:'reciepeapp'
});
module.exports = con
the ORM
const con = require('./db')
The ORM
const orm = {
insertOne: function (values, cb) {
const sqlQuery = "INSERT INTO authentication(username,password) VALUES ?";
con.query(sqlQuery, [values],function (err, data) {
if (err) {
console.log(err)
cb(err, null);
} else {
cb(null, data);
}
});
},
}
module.exports = orm;
The route.js
Here I insert the data obtained during registration (register index html) into a database. It's working well but I want to redirect to home page.
const express = require('express');
const app = express()
const router = express.Router()
const bcrypt = require('bcrypt');
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
const orm = require('../models/orm')
router.get('/',(req,res)=>
res.render('home')
)
router.get('/login',(req,res)=>
res.render('login')
)
router.get('/register',(req,res)=>
res.render('register')
)
router.post("/register", async (req, res) =>{
try {
const hashedPassword = await bcrypt.hash(req.body.password,10)
values = { username: req.body.name,
password:hashedPassword }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
values = { username: values.username,
password: values.password }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
**return res.send({
username: values.username,
password: values.password
});**
});
});
}
catch {
}
});
module.exports = router
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
To do this you need to use express's redirect method.
Example:
var express = require('express');
var app = express();
const urlBase = 'localhost:3000/'
app.post('/', function(req, res) {
const redirectUrl = "index.html"
res.redirect(urlBase + redirectUrl);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Docs: Express 4.x Docs

Categories

Resources