Boundary Not Found Why? - node.js

This is my register page and here ı m handling multipart form ...
import React, { useEffect, useState } from "react";
import { Next } from "react-bootstrap/esm/PageItem";
import { Link } from "react-router-dom";
import CheckedCompany from "./includes/CheckedCompany";
import axios from "axios";
export default function Sigin() {
const [companyType, setCompanyType] = useState(false);
const clickHandlerCompanyType = (event) => {
setCompanyType(!companyType);
console.log("Im here");
};
const [checked, setchecked] = useState(false);
const checkedPerson = (event) => {
setchecked(!checked);
};
const [name, setName] = useState("");
const [surname, setSurname] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [image, setImage] = useState("");
const submitHandler = (e) => {
axios({
url: "http://localhost:5000/user/register",
method: "POST",
data: {
name,
surname,
email,
password,
userType: checked ? "2" : "1",
image,
},
headers: {
"Content-Type": "multipart/form-data",
},
withCredentials: true,
crossDomain: true,
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
};
return (
<div class="container pt-5 mb-2">
<div class="row">
<div class=" container col-md-12 ">
<div class=" container card my-1">
<h5 class="card-title text-center">Yeni Kayıt</h5>
<div class="card-body">
<div className="row ">
<div className="col-6 ps-5">
<div class="mb-3 form-check">
{" "}
<label class="form-check-label" for="exampleCheck2">
Bireysel
</label>
<input
checked={!checked}
onChange={checkedPerson}
type="radio"
class="form-check-input"
name="flexRadioDefault"
/>
</div>
</div>
<div className="col-6 ps-5">
<div class="mb-3 form-check">
<input
onChange={checkedPerson}
type="radio"
class="form-check-input"
name="flexRadioDefault"
></input>
<label class="form-check-label" for="exampleCheck2">
İşletme
</label>
</div>
</div>
</div>
<form onSubmit={submitHandler}>
<div class="mb-3">
<label for="formFile" class="form-label">
Resim
</label>
<input
class="form-control"
type="file"
name="image"
onChange={(e) => {
setImage(e.target.files[0]);
console.log(e.target.files[0]);
}}
/>
</div>
<div class="mb-3">
<label for="name" class="form-label">
Adınız
</label>
<input
type="text"
class="form-control"
name="name"
onChange={(e) => setName(e.target.value)}
></input>
</div>
<div class="mb-3">
<label for="surname" class="form-label">
Soyadınız
</label>
<input
type="text"
class="form-control"
name="surname"
onChange={(e) => setSurname(e.target.value)}
></input>
</div>
<div class="mb-3">
<label for="email" class="form-label">
E-posta adresiniz
</label>
<input
type="email"
class="form-control"
name="email"
onChange={(e) => setEmail(e.target.value)}
></input>
</div>
<div className="mb-3">
{" "}
<label for="password" class="form-label">
Şifre
</label>
<input
type="password"
class="form-control"
name="password"
aria-describedby="passwordHelp"
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{checked
? CheckedCompany({
companyType,
clickHandlerCompanyType,
setCompanyType,
})
: null}
<div class="mb-3">
<div id="passwordHelp" class="form-text">
şifremi unuttum
</div>
</div>
<div class="mb-3 form-check">
<input
type="checkbox"
class="form-check-input"
id="exampleCheck1"
></input>
<label class="form-check-label" for="exampleCheck1">
Bireysel Üyelik Sözleşmesini ve Ekleri'ni{" "}
Kabul ediyorum
</label>
</div>
<div class="mb-3 form-check">
<input
type="checkbox"
class="form-check-input"
id="exampleCheck2"
></input>
<label class="form-check-label" for="exampleCheck2">
İletişim bilgilerime kampanya, tanıtım ve reklam içerikli
ticari elektronik ileti gönderilmesine, bu amaçla kişisel
verilerimin işlenmesine ve tedarikçilerinizle paylaşılmasına
izin veriyorum
</label>
</div>
<p class="card-text text-center">
<button type="submit" class="btn btn-primary">
Üye Ol
</button>
</p>
</form>
</div>
</div>
<div class="card">
<div class="card-body">
Bu sayfadaki bilgiler 4teker.com üyeliği için alınmaktadır.
Kişisel verilerin korunması hakkında detaylı bilgiye{" "}
buradan ulaşabilirsiniz.
</div>
</div>
</div>
</div>
</div>
);
}
I'm sending the form with axios to api
const express = require("express");
const app = express();
const cors = require("cors");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const mongoDbStore = require("connect-mongodb-session")(session);
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
require("dotenv").config();
const port = process.env.PORT;
//Routes
const postRoutes = require("./routes/post.route");
const userRoutes = require("./routes/user.route");
//Middlewares
const store = new mongoDbStore({
uri: process.env.ATLAS_URI,
collection: "Sessions",
});
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./public/img/");
},
filename: function (req, file, cb) {
cb(
null,
file.fieldname + "-" + Date.now() + path.extname(file.originalname)
);
},
});
app.use(express.static("public"));
app.use(multer({ storage }).single("image"));
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 36000000,
},
store,
})
);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
app.use(express.json());
//DB
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Db is connected");
});
app.use("/user", userRoutes);
app.use("/post", postRoutes);
app.listen(port, () => {
console.log("Port 5000 is listening...");
});
I mean there shouldnt be any problem ,but there it is :d
Can you guys help me ?
Btw error is on below.
Error: Multipart: Boundary not found
at new Multipart (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\busboy\lib\types\multipart.js:58:11)
at Multipart (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\busboy\lib\types\multipart.js:26:12)
at Busboy.parseHeaders (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\busboy\lib\main.js:71:22)
at new Busboy (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\busboy\lib\main.js:22:10)
at multerMiddleware (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\multer\lib\make-middleware.js:33:16)
at Layer.handle [as handle_request] (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:275:10)
at serveStatic (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\serve-static\index.js:75:16)
at Layer.handle [as handle_request] (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:275:10)

Related

req.body.fname notworking in express it shows result as undefined

code
I am not sure why the below does not work .I tried to add app.use(express.json()); in index.js but still not working. Any idea on how to solve this?
when I console.log it shows undefined
I am trying to console log the data that is submitted in the html
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
const { path } = require('express/lib/application');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static('public'))
app.get('/', function (req, res) {
res.sendFile(__dirname + "/Signup.html")
})
app.post('/Signup.html', function (req, res) {
var fname = req.body.fname
var lname = req.body.lastname
var email = req.body.email
console.log(fname, lname, email)
})
app.listen(3000, function () {
console.log("Running in 3000 ")
})
HTML
this is the html code
<form action="/Signup.html" method="post" >
<img class="mb-4" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcST1ViA_OmDA31rfd8ooDSmjLUeuh-HujXTwA&usqp=CAU" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Please sign in</h1>
<div class="form-floating top">
<input type="text" name="fname" id="fname" class="form-control top" placeholder="First Name" required>
<label for="floatingInput">First Name</label>
</div>
<div class="form-floating middle">
<input type="text" class="form-control middle" name="lastname" placeholder="Last Name">
<label for="floatingPassword">Last Name</label>
</div>
<div class="form-floating bottom">
<input type="email" class="form-control bottom" name="email" placeholder="email">
<label for="floatingPassword">Email</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign Me Up</button>
<p class="mt-5 mb-3 text-muted">© The App Brewery</p>
</form>

How to POST form data from React Front End to my backend?

I'm trying to figure out how to send React Form data to my backend and into my mongoDB database. I can create an admin and log them in when testing this out in postman but I cannot figure out how to send the form data from React to my backend. I use Nodejs and Express on the backend.
This is my form
import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import dotenv from "dotenv";
dotenv.config();
const baseUrl = process.env.REACT_APP_BASE_URL;
export const Register = () => {
const [admin, setAdmin] = useState({
username: '',
email: '',
password: ''
})
// define an admin
const { username, email, password } = admin
// use user input data to set the admin
const handleChange = (e) => {
e.preventDefault()
setAdmin({
...admin,
[e.target.name]: e.target.value
})
}
const registerAdmin = async (admin) => {
const res = await fetch(`${baseUrl}/admins/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(admin),
})
console.log(res)
}
// once admin is set, pass that data when submitted
const handleSubmit = (e) => {
e.preventDefault()
// call API function to send admin data to backend
registerAdmin(admin)
// after admin is sent to the backend, reset state
setAdmin({
username: '',
email: '',
password: ''
})
}
return (
<>
<form onSubmit={handleSubmit}>
<section className="hero is-primary is-fullheight">
<div className="hero-body">
<div className="container">
<div className="columns is-centered">
<div className="column is-5-tablet is-4-desktop is-3-widescreen">
<form action="" className="box">
<h1 className="has-text-centered">Register Form</h1>
<div className="field">
<label htmlFor="" className="label">Username</label>
<div className="control has-icons-left">
<input type="text" value={username} name="username" onChange={handleChange} placeholder="username" className="input" required />
<span className="icon is-small is-left">
<i className="fa fa-envelope"></i>
</span>
</div>
</div>
<div className="field">
<label htmlFor="" className="label">Email</label>
<div className="control has-icons-left">
<input type="email" value={email} name="email" onChange={handleChange} placeholder="e.g. bobsmith#gmail.com" className="input" required />
<span className="icon is-small is-left">
<i className="fa fa-envelope"></i>
</span>
</div>
</div>
<div className="field">
<label htmlFor="" className="label">Password</label>
<div className="control has-icons-left">
<input type="password" value={password} name="password"
onChange={handleChange} placeholder="*******" className="input" required />
<span className="icon is-small is-left">
<i className="fa fa-lock"></i>
</span>
</div>
</div>
<div className="field">
<Link to='/' type="submit" className="button is-success">
Register
</Link>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</form>
</>
)
}
This is the code in my server.
import express from 'express';
import session from 'express-session'
import connectMongo from 'connect-mongo';
import db from './db.js'
// allows us to take in incoming post request body
import bodyParser from 'body-parser'
import dotenv from 'dotenv';
// bring in the admins routes
import adminsRoutes from './routes/admins.js'
dotenv.config();
const app = express();
const PORT = process.env.PORT;
const MongoStore = connectMongo(session);
let sessionOptions = session({
secret: process.env.SECRET,
store: new MongoStore({client: db}),
resave: false,
saveUninitialized: false,
cookie: {maxAge: 1000 * 60 * 60 * 24, httpOnly: true}
})
app.use(sessionOptions)
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// tell express to use the admins routes
// set the starting path for all the routes in the admins.js
app.use('/admins', adminsRoutes);
// route to the homepage
app.get('/', (req, res) => res.send('Hello from home page'));
app.listen(PORT, () => {
console.log(`Server is listening on port: ${PORT}`)
})
Any pointers or tips in any of my code is greatly appreciated.
Thank you for your time!

Insert form data from nodejs to mongodb

const express = require("express");
const handlebars = require("express-handlebars");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine(".hbs", handlebars({ defaultLayout: "main", extname: ".hbs" }));
app.set("view engine", ".hbs");
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
mongoose.Promise = global.Promise;
mongoose.connect(
"mongodb://usresa:passcode#mongodb-rukshi-shard-00-00.nerbj.gcp.mongodb.net:27017,mongodb-rukshi-shard-00-01.nerbj.gcp.mongodb.net:27017,mongodb-rukshi-shard-00-02.nerbj.gcp.mongodb.net:27017/db_name?ssl=true&replicaSet=atlas-dxrzem-shard-0&authSource=admin&retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true }
);
const nameSchema = new mongoose.Schema({
name: String,
naquantityme: String,
description: String,
});
const User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
res.render("login", { layout: "loginlayout" });
});
app.get("/home", (req, res) => {
res.render("dashboard", { layout: "main" });
});
app.use("/AddProduct", (req, res) => {
res.render("AddProduct", { layout: "main" });
});
app.post("/addproductform", (req, res) => {
var myData = new User(req.body);
myData
.save()
.then((item) => {
res.send("Product saved to database");
})
.catch((err) => {`enter code here`
res.status(400).send("Unable to save to database");
});`enter code here
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
///// Front End
<form id="form_validation" method="post" action="/addproductform">
<div class="form-group form-float">
<input type="text" class="form-control" placeholder="Product Name" name="name"
required>
</div>
<div class="form-group form-float">
<input type="text" class="form-control" placeholder="Quantity" name="quantity"
required>
</div>
{{!-- <div class="form-group">
<div class="radio inlineblock m-r-20">
<input type="radio" name="gender" id="male" class="with-gap" value="option1">
<label for="male">Male</label>
</div>
<div class="radio inlineblock">
<input type="radio" name="gender" id="Female" class="with-gap" value="option2"
checked="">
<label for="Female">Female</label>
</div>
</div> --}}
<div class="form-group form-float">
<textarea name="description" cols="30" rows="5" placeholder="Description"
class="form-control no-resize" required></textarea>
</div>
{{!-- <div class="form-group">
<div class="checkbox">
<input id="checkbox" type="checkbox">
<label for="checkbox">I have read and accept the terms</label>
</div>
</div> --}}
<button class="btn btn-raised btn-primary waves-effect" id="submitDetails"
name="submitDetails" type="submit">SUBMIT</button>
</form>
This is appjs code. Rest I have AddProduct in views folder.
The default setting for accesing the view is from views folder.
This addproduct form is not submitting the datat to database.
How do we change the route of different views
This addproduct form is not submitting the datat to database.
This addproduct form is not submitting the datat to database.
This addproduct form is not submitting the datat to database.

SyntaxError: Unexpected token / in .... while compiling ejs | Node.js with MongoDB

When I try and use <% include ./partials/messages %>, <%= include ./partials/messages %>, or even <%= include ./partials/messages { %>, among my file that contains
<!-- REGISTER.EJS -->
<div class="row mt-5">
<div class="col-md-6 m-auto">
<div class="card card-body">
<h1 class="text-center mb-3">
<i class="fas fa-user-plus"></i> Register
</h1>
<% include ./partials/messages %>
<form action="/users/register" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input
type="name"
id="name"
name="name"
class="form-control"
placeholder="Enter Name"
value="<%= typeof name != 'undefined' ? name : '' %>"
/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
name="email"
class="form-control"
placeholder="Enter Email"
value="<%= typeof email != 'undefined' ? email : '' %>"
/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
id="password"
name="password"
class="form-control"
placeholder="Create Password"
value="<%= typeof password != 'undefined' ? password : '' %>"
/>
</div>
<div class="form-group">
<label for="password2">Confirm Password</label>
<input
type="password"
id="password2"
name="password2"
class="form-control"
placeholder="Confirm Password"
value="<%= typeof password2 != 'undefined' ? password2 : '' %>"
/>
</div>
<button type="submit" class="btn btn-primary btn-block">
Register
</button>
</form>
<p class="lead mt-4">Have An Account? Login</p>
</div>
</div>
</div>
I receive the follow error "SyntaxError: Unexpected token / in .... while compiling ejs". I am using this to add immediate feedback to users who try and register such as "password invalid" or "email already exist." I believe I have my messages.ejs file set up correctly as such:
<% if(typeof errors != 'undefined') { %>
<% errors.forEach(function(error) { %>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<%= error.msg %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<%}); %>
<% } %>
<% if(success_msg != '') { %>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<%= success_msg %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% } %>
<% if(error_msg != '') { %>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<%= error_msg %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% } %>
<% if(error != '') { %>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<%= error %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% } %>
I am pretty lost. I believe I have added the const example = require('example'); files correctly. My app.js file looks like
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const app = express();
// Passport Config
require('./config/passport')(passport);
// DB Config
const db = require('./config/keys').mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
app.use(express.static( 'public' ));
// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
// Bodyparser
app.use(express.urlencoded({ extended: false }));
// Express Session
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}))
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
// Connect Flash
app.use(flash());
// Global Variables
app.use((req, res, next) => {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
// Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));
My file structure looks like:
>config
auth.js
keys.js
passport.js
>models
User.js
>node_modules
>public
>routes
index.js
users.js
>views
>partials
messages.ejs
dashboard.ejs
layout.ejs
login.ejs
register.ejs
welcome.ejs
.gitignore
app.js
package-lock.json
package.json
README.md
Does anyone have any ideas?
Error message looks like this:
SyntaxError: Unexpected token / in C:\Users\jreed\Desktop\appproject\views\register.ejs while compiling ejs
If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass `async: true` as an option.
at new Function (<anonymous>)
at Template.compile (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:626:12)
at Object.compile (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:366:16)
at handleCache (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:215:18)
at tryHandleCache (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:254:16)
at View.exports.renderFile [as engine] (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:459:10)
at View.render (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\application.js:640:10)
at Function.render (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\response.js:1012:7)
at ServerResponse.res.render (C:\Users\jreed\Desktop\appproject\node_modules\express-ejs-layouts\lib\express-layouts.js:77:18)
at router.get (C:\Users\jreed\Desktop\appproject\routes\users.js:13:43)
at Layer.handle [as handle_request] (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\router\layer.js:95:5)
Here is my users.js file:
<!-- USERS.JS -->
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
// User Model
const User = require('../models/User');
// Login Page
router.get('/login', (req, res) => res.render('login'));
// Register Page
router.get('/register', (req, res) => res.render('register'));
// Register Handle
router.post('/register', (req, res) => {
const {name, email, password, password2} = req.body;
let errors = [];
// Check required fields
if (!name || !email || !password || !password2) {
errors.push({msg: 'Please enter all fields'});
}
// Check passwords match
if (password != password2) {
errors.push({msg: 'Passwords do not match'});
}
// Check password length
if (password.length < 6) {
errors.push({msg: 'Password must be at least 6 characters'});
}
if (errors.length > 0) {
res.render('register', {errors, name, email, password, password2});
} else { // Validation passed
User.findOne({email: email}).then(user => {
if (user) { // User Exists
errors.push({msg: 'Email is already registered'})
res.render('register', {errors, name, email, password, password2});
} else {
const newUser = new User({
name,
email,
password
});
// Hash Password
bcrypt.genSalt(10, (err, salt) => bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
// Set password to hashed
newUser.password = hash;
// Save user
newUser.save()
.then(user => {
req.flash('success_msg', 'Congratulations! You are now registered and can log in.');
res.redirect('/users/login');
})
.catch(err => console.log(err));
}))
}
});
}
});
// Login Handle
router.post('/login', (req, res, next) => {
passport.authenticate('local',{
successRedirect: '/dashboard',
failureRedirect: '/users/login',
failureFlash: true
})(req, res, next);
});
// Logout Handle
router.get('/logout', (req, res) => {
req.logout();
req.flash('success_msg', 'You are logged out.');
res.redirect('/users/login');
});
module.exports = router;
I think I solved it!
<%- include ('partials/messages') %>
I have no idea why that is the only method that works though, trying to research it now.

Node.js/Express post request unsuccessful

I have a simple CRUD app in Node.js/Express. It's an order intake form to post data to a MongoDB collection.
I cannot for the life of me see why this POST (CREATE) route is not succeeding. I’ve been troubleshooting this all morning. My other routes run just fine as validated with my console.logs.
Here is my orders route file (/routes/orders.js):
var express = require("express");
var router = express.Router();
var Order = require("../models/order.js");
// Load Keys ===================================================================
const keys = require('../config/keys');
// INDEX ROUTE - show all orders
router.get("/", isLoggedIn, function(req, res){
// Get all orders from DB
Order.find({}, function(err, allOrders){
if(err){
console.log(err);
} else {
res.render("orders", {orders:allOrders});
//Test to see if this returns the number of records in the collection
console.log("There are currently " + allOrders.length + " orders.");
}
});
});
// CREATE ROUTE - add new order to the DB
router.post("/", isLoggedIn, function(req, res){
// get data from form and add to newOrder object
var date = req.body.date;
var territory = req.body.territory;
var principal = req.body.principal;
var customer = req.body.customer;
var representative = req.body.representative;
var amount = req.body.amount;
var newOrder = {date: date, territory: territory, principal: principal, customer: customer, representative: representative, amount: amount};
// Create a new order and save to DB
Order.create(newOrder, function (err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to orders page
res.redirect("/");
console.log("New order created (orders route file).");
}
});
});
// NEW ROUTE - show form to create new customer
router.get("/new", isLoggedIn, function(req, res){
res.render("new.ejs");
console.log("This is coming from the order route js file.");
});
This is my new.ejs template file with the form:
<div class="container container-new py-5">
<div class = "row">
<div class="col-lg-12 orders-title">
<h2>New Order</h2>
</div>
</div>
<div class="row">
<div class="col-md-10 mx-auto">
<form action="/orders" method="POST">
<div class="form-group row">
<div class="col-sm-3">
<label for="inputDate">Date</label>
<input type="text" class="form-control" id='datetimepicker' name="date">
</div>
<div class="col-sm-3">
<label for="inputTerritory">Territory</label>
<select id="selectTerr" class="form-control" name="territory">
<option>Choose a territory</option>
</select>
</div>
<div class="col-sm-6">
<label for="inputPrincipal">Principal</label>
<select id="selectPrin" class="form-control" name="principal">
<option>Choose a principal</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-5">
<label for="inputCustomer">Customer</label>
<select id="selectCust" class="form-control" name="customer">
<option>Choose a customer</option>
</select>
</div>
<div class="col-sm-4">
<label for="inputRepresentative">Sales Rep</label>
<select id="selectRep" class="form-control" name="representative">
<option>Choose a rep</option>
</select>
</div>
<div class="col-sm-3">
<label for="inputState">Total</label>
<input type="text" class="form-control" id="inputTotal" name="amount">
</div>
</div>
<div class="form-group new-buttons">
<button type="button" class="btn btn-cancel btn-default btn-primary px-4">Clear</button>
<button type="button" class="btn btn-submit btn-default btn-primary px-4">Submit</button>
</div>
</form>
</div>
</div>
<div class = "row row-back">
<div class="col-lg-12 orders-title">
Back to Main
</div>
</div>
</div>
app.js:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose"),
methodOverride = require("method-override"),
seedDB = require("./seeds");
// seedDB();
// Requiring Routes ============================================================
var ordersRoutes = require("./routes/orders"),
indexRoutes = require("./routes/index");
// Load Keys ===================================================================
const keys = require('./config/keys');
// Map global promises
mongoose.Promise = global.Promise;
// Mongoose Connect ============================================================
mongoose.connect(keys.mongoURI, {
useMongoClient: true
})
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
//==============================================================================
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(methodOverride("_method"));
app.use(indexRoutes);
app.use("/orders", ordersRoutes);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`server started on port ${port}`));

Resources