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.
Related
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)
So I installed body parser via
npm i install express body-parser
and I wrote a simple code designed to input a user into an array after they complete a registration form.
but when I console.log the user it returns undefined for both email and password
here is the server code
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const PORT = 3000;
var Users = [{"email":"mike#gmail.com", "password":"456"}];
app.get('/', (req, res) => {
res.render('index.ejs')
})
app.get('/Register.ejs', (req, res) => {
res.render('Register.ejs')
})
app.post('/views/Register.ejs', (req, res) =>
{
const newUser = {
email: req.body.email,
password: req.body.password
};
Users.push(newUser);
res.json(req.body.email);
console.log(Users)
}
)
app.listen(PORT);
here is the html for the register page
<h1>Please Register</h1>
<body>
<form action="/views/Register.ejs" method="POST">
<div class="div">
<label for="email">Enter Email</label>
<input type="email" id="email"for="email" id="email" required>
</div>
<div class="div">
<label for="password">Enter new password</label>
<input type="password" for="password" id="password" required>
</div>
<button type="submit"> Register </button>
</form>
</body>
Only installing body-parser is not enough. You have to put them in the code as middleware.
Top of the code use:
var bodyParser = require('body-parser');
and then use the code in somewhere middle of the code:
app.use(bodyParser.json())
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!
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}`));
I'm just learning node and JS and therefore I built a very simple express-application with mongodb. The application is supposed to render a handlebars-template with a form to add users to the database.
My Problem is: When I send my form via the browser, req.body is always empty. When I send it via postman it works and the user gets added to my database. Why is that and what is missing for body-parser to parse my html-form.
Here is what I have so far:
app.js
const express = require('express'),
app = express(),
createError = require('http-errors'),
path = require('path'),
logger = require('morgan'),
bodyParser = require('body-parser'),
exphbs = require('express-handlebars');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev')); // Log requests to API using morgan
app.set('views', './views');
app.engine('hbs', exphbs({
defaultLayout: 'main',
extname: 'hbs'
}));
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', require('./routes/routes'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = process.env.NODE_ENV === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
views/adminAdd.hbs
<div class="row">
<form class="col s12" id="reg-form" action="/admin/add" name="add-form" enctype="application/x-www-form-urlencoded" method="post">
<div class="row py-md-2">
<div class="input-field col col-sm-6">
<input id="firstname" type="text" class="validate" required>
<label for="firstname">First Name</label>
</div>
</div>
<div class="row py-md-2">
<div class="input-field col col-sm-6">
<input id="lastname" type="text" class="validate" required>
<label for="lastname">Last Name</label>
</div>
</div>
<div class="row py-md-2">
<div class="input-field col col-sm-6">
<input id="email" type="email" class="validate" required>
<label for="email">Email</label>
</div>
</div>
<div class="row py-md-2">
<div class="input-field col col-sm-6">
<input id="password" type="password" class="validate" minlength="6" required>
<label for="password">Password</label>
</div>
</div>
<div class="row py-md-2">
<div class="input-field col-sm-6">
<button class="btn btn-large btn-register btn-primary" type="submit" name="adduser">Add User</button>
</div>
</div>
</form>
</div>
controllers/adminController
var util = require("util"),
adminUser = require("../models/adminUserModel");
exports.admin = function(req, res) {
res.render('admin', {
showNavBar: true,
showFooter: false,
title: 'Admin'
});
};
exports.adminAddGET = function(req, res) {
res.render('adminAdd', {
showNavBar: true,
showFooter: false,
title: 'Admin Add'
});
};
exports.adminAddPOST = function(req, res) {
console.log("req.body=" + util.inspect(req.body));
if(!req.body.firstname) {
res.json({ success: false, message: 'Please provide firstname.' });
} else if (!req.body.lastname) {
res.json({ success: false, message: 'Please provide lastname.' });
} else if (!req.body.email) {
res.json({ success: false, message: 'Please provide email.' });
} else if (!req.body.password) {
res.json({ success: false, message: 'Please provide password.' });
} else {
console.log("All Fields filled");
var newAdminUser = new adminUser({
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
password: req.body.password
});
console.log("newAdminUserObject=" + util.inspect(newAdminUser));
// Attempt to save the user
newAdminUser.save(function(err) {
if (err) {
console.log("error:" + err);
return res.json({ success: false, message: 'ERROR - Didnt work' });
}
console.log("success");
res.json({ success: true, message: 'User added successfully!' });
});
}
};
routes/routes.js
var express = require('express'),
router = express.Router(),
adminController = require('../controllers/adminController'),
indexController = require('../controllers/indexController');
router.get('/', indexController.index);
router.get('/admin', adminController.admin);
router.get('/admin/add', adminController.adminAddGET);
router.post('/admin/add', adminController.adminAddPOST);
module.exports = router;
When sending the following form via postman...
Postman x-www-form-urlencoded
I see the following output in my terminal and the user is added successfully to my mongodb:
req.body={ firstname: 'dan',
lastname: 'dan',
email: 'dan#dan.de',
password: 'dandan' }
All Fields filled
newAdminUserObject={ role: 'Admin',
_id: 5b106939991dda2404c0dc6a,
firstname: 'dan',
lastname: 'dan',
email: 'dan#dan.de',
password: 'dandan' }
success
When I send the form via the browser, I get the following output:
req.body={ adduser: '' }
and in the browser I see the following:
browser output
From my perspective I'm sending the form with x-www-form-urlencoded in both ways to the same address.
Your form input elements are missing 'name' attributes. The reason you are getting { adduser: '' } is because the only input element in the form that has a name attribute is the button element.
<input id="firstname" name="firstname" type="text" class="validate" required>
<input id="email" name="email" type="email" class="validate" required>
...etc