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
Related
I'm trying to register users and then authenticate them using passport-local-mongoose. When I try to register a user I get the error 'User validation failed: password: Path password is required.' I got rid of the error by changing required to false for password field of my userSchema in 'userModel.js' but I assume that password has to be required. Does anyone know of a better solution?
And moreover I don't understand why it's giving me the error when I've included a password field for the user.
And when I do change required to false for password, the registration works and I end up with the user stored in the Users collection, but then the authentication gives me a Status 400 Bad Request error and over there I'm completely stuck.
This is my server.js
import express from "express";
import mongoose from "mongoose";
import userRouter from "./routers/userRouter.js";
import session from "express-session";
import bodyParser from "body-parser";
import passport from "passport";
import User from "./models/userModel.js";
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(session({
secret: "some secret sentence",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(process.env.MONGODB_URL || "mongodb://localhost/somedatabase", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use("/api/users", userRouter);
app.get("/", (req, res) => {
res.send("Server is ready");
});
app.use((err, req, res, next) => {
res.status(500).send({ message: err.message });
});
app.listen(5000, () => {
console.log("Serve at http://localhost:5000");
});
userRouter.js:
import express from "express";
import expressAsyncHandler from "express-async-handler";
import User from "../models/userModel.js";
import passport from "passport";
import passportLocalMongoose from "passport-local-mongoose";
userRouter.post("/register", expressAsyncHandler(async (req, res) =>{
const createdUser = new User({name: req.body.name, username: req.body.email})
User.register(createdUser, req.body.password, async function(err, user){
if(err){
console.log(err);
res.redirect("http://localhost:3000/register");
}else{
passport.authenticate("local")(req ,res , function(){
console.log("authenticate successful");
res.send({
_id: createdUser._id,
user: createdUser.name,
email: createdUser.username,
isAdmin: createdUser.isAdmin,
token: generateToken(user)
})
})
}
})
userModel.js
import mongoose from "mongoose";
import passport from "passport";
import passportLocalMongoose from "passport-local-mongoose";
const userSchema = new mongoose.Schema(
{
name: {type: String, required: true},
username: {type: String, required: true, unique: true},
password: {type: String, required: true},
isAdmin: {type: Boolean, default: false, required: true},
},
{
timestamps: true,
}
);
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model("User", userSchema);
export default User;
RegisterScreen.jsx
import React,{ useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { register } from "../actions/userActions.js"
export default function RegisterScreen(props){
const[email,setEmail] = useState("");
const[name,setName] = useState("");
const[password, setPassword] = useState("");
const[confirmPassword, setConfirmPassword] = useState("");
const redirect = props.location.search? props.location.search.split("=")[1] : "/";
const userRegister = useSelector((state) => state.userRegister);
const {userInfo , loading, error} = userRegister;
const dispatch = useDispatch();
const submitHandler = (e) =>{
e.preventDefault();//prevents refresh
if(password !== confirmPassword){
alert("Password and confirm password do not match")
}else{
dispatch(register(name, email, password));
}
};
useEffect(() =>{
if(userInfo){
props.history.push(redirect);
}
}, [userInfo, redirect, props.history]);
return (
<div className="container mt-5">
<h1>Register</h1>
{
loading && <h2>Loading</h2>
}
{ error && <h1>{error}</h1>}
<div className="row">
<div className="col-sm-8">
<div className="card">
<div className="card-body">
<form onSubmit={submitHandler}>
<div className="form-group">
<label htmlFor="email">Name</label>
<input
type="text"
id="name"
className="form-control"
placeholder="Enter name"
required
onChange={(e) => setName(e.target.value)}
></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
className="form-control"
placeholder="Enter email"
required
onChange={(e) => setEmail(e.target.value)}
></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
placeholder="Enter password"
className="form-control"
required
onChange={(e) => setPassword(e.target.value)}
></input>
</div>
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
type="password"
id="confirmPassword"
placeholder="Enter password"
className="form-control"
required
onChange={(e) => setConfirmPassword(e.target.value)}
></input>
</div>
<button type="submit" className="btn btn-dark">Register</button>
<div>
Already have an account? {' '}
<Link to={`/login?redirect=${redirect}`}>Log into your account</Link>
</div>
</form>
</div>
</div>
</div>
<div className="col-sm-4">
<div className="card">
<div className="card-body">
<a className="btn btn-block btn-social btn-google" href="/auth/google" role="button">
<i className="fab fa-google"></i>
Sign In with Google
</a>
</div>
</div>
</div>
</div>
</div>)
}
remove the password field from the model. Passport takes care of that
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.
I am using ejs engine instead of pug. When I click register button, I got errors undefined in my register view. There was only little chance that I can get the validation messages, but when I click other links and then back to the register page, the same error occurred again.
Here's my code:
app.js
//app.js code
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var expressValidator = require('express-validator');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var upload = multer({dest: './uploads'});
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Handle Sessions
app.use(session({
secret:'secret',
saveUninitialized: true,
resave: true
}));
// Passport
app.use(passport.initialize());
app.use(passport.session());
// Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
user.js
//user.js code
var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({dest: 'uploads/'});
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('members', {page_name : 'members'});
});
router.get('/register', function(req, res, next) {
res.render('register', { page_name: 'register' });
});
router.post('/register', upload.single('profileimage'), function(req, res) {
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;
if(req.file){
console.log("uploading file");
var profileimage = req.file.filename;
} else{
var profileimage = "noimage.jpg";
}
req.checkBody('name','Name field is required').notEmpty();
req.checkBody('email','Email field is required').notEmpty();
req.checkBody('email','Email is not valid').isEmail();
req.checkBody('username','Username field is required').notEmpty();
req.checkBody('password','Password field is required').notEmpty();
req.checkBody('password2','Passwords do not match').equals(req.body.password);
// Check Errors
errors = req.validationErrors();
//var errors = JSON.stringify(req.validationErrors());
if(errors){
console.log("errors: " + errors);
res.render('register', {errors: errors});
} else{
console.log('No Errors');
res.render("/");
}
});
router.get('/login', function(req, res, next) {
res.render('login', { page_name: 'login' });
});
module.exports = router;
register.ejs
//register.ejs code
<%include layout%>
<div class="container">
<% if(errors){errors.forEach(function(error){%>
<div class="alert alert-danger"><%= error.msg %></div>
<% })} %>
<h4>register</h4>
<form action="/users/register" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleFormControlInput1">Name</label>
<input type="text" class="form-control" name="name" placeholder="John">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" class="form-control" name="email" placeholder="name#example.com">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Username</label>
<input type="text" class="form-control" name="username" placeholder="username">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Password</label>
<input type="password" class="form-control" name="password" placeholder="password">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Confirm Password</label>
<input type="password" class="form-control" name="password2" placeholder="confirm password">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Profile Image</label>
<input type="file" class="form-control" name="profileimage" >
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
Error
ReferenceError: /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/views/register.ejs:5
3| <div class="container">
4|
>> 5| <% if(errors){errors.forEach(function(error){%>
6|
7| <div class="alert alert-danger"><%= error.msg %></div>
8|
errors is not defined
at eval (eval at compile (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:549:12), <anonymous>:22:8)
at returnedFn (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:580:17)
at tryHandleCache (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:223:34)
at View.exports.renderFile [as engine] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:437:10)
at View.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/view.js:127:8)
at tryRender (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/application.js:640:10)
at Function.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/application.js:592:3)
at ServerResponse.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/response.js:971:7)
at /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/routes/users.js:12:9
at Layer.handle [as handle_request] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/layer.js:95:5)
at /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:335:12)
at next (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:275:10)
That's because you are trying to access a non existing variable, note that errors variable is only generated and returned to the view if there where validation errors in your form, otherwise it's undefined, that's why in your condition you have to check if errors variable exists, Like this:
if (typeof errors !== 'undefined') { ...
Note: The typeof operator returns a string: the type of the variable, if the variable is not declared it will return undefined
npm uninstall express-validator --save
npm install express-validator#2.20.8 --save
Have a look at my code, it is working
in file 'index.js'
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Home' ,
success:false,
errors:req.session.errors ,
success:req.session.success });
req.session.errors=null;
});
//////////////checking the form validation
router.post('/submit', function(req, res, next) {
req.check('email','Invalid Email Address!!!!!').isEmail();// it's an built in exprexx validator, but we can also write our own
req.check('password','Pssword lenght must be greater than 5!! ').isLength({min:5});
req.check('password','Password is not confirmed!!').equals(req.body.confirmpassword);
var errors=req.validationErrors();
if (errors){
req.session.errors=errors;
req.session.success=false;
}
else{
req.session.success=true;
}
res.redirect('/');
});
module.exports = router;
in file 'index.ejs'
<h1>Fill the form below..</h1><h1></h1>
<h1>It's an example of Express Validator..</h1><h1></h1>
<% if (success) { %>
<h1><span class="badge badge-success">Congrats!! Form validation is secceded!!!</span></h1>
<% } else { %>
<% if (errors) { %>
<div class="alert alert-danger" role="alert">
<h1><span class="badge badge-danger">Errors Occured!! </span></h1>
<% errors.forEach(function(errors) { %>
<h5><%= errors.msg %> </h5>
<% }); %>
</div>
<% } else { %>
<form action="/submit" method="POST">
<div class="form-row">
<div class="col-7">
<input type="email" class="form-control" id="email" placeholder="email" name="email">
</div>
<div class="col">
<input type="password" class="form-control" id="password" placeholder="password" name="password">
</div>
<div class="col">
<input type="password" class="form-control" id="confirmpassword" placeholder="confirmpassword" name="confirmpassword">
</div>
</div>
<h1></h1>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<% } %>
<% } %>
And of course don't forget to add this lines in 'app.js' file:
//adding validator and session
app.use(expressValidator());
app.use(expressSession({secret:'max',saveUninitialized:false,resave:false}));
<% if(locals.errors){locals.errors.forEach(function(error){%>
<div class="alert alert-danger"><%= error.msg %></div>
<% })} %>
I am trying to store some user information in a MongoDB database.
From the front-end (AngularJS) on localhost:9000 I make a POST to the backend (express on localhost:3000)
I'm getting in the header information all the data, including the email-address.
but in the body email is undefined??
Console from Node server:
Console from Web browser:
I must do something wrong with the body parser?
Front-end:
registration View:
<form ng-submit="submit()" name="register" class="form-signin" novalidate>
<h1 class="form-signin-heading text-muted">Register</h1>
<input name="email" ng-model="email" type="email" class="form-control" placeholder="Email address" required autofocus="" required>
<p class="help-block" ng-show="register.email.$dirty && register.email.$invalid">Please enter a proper email.</p>
<input name="password" ng-model="password" type="password" class="form-control" placeholder="Password" required>
<input name="password_confirm" ng-model="password_confirm" type="password" class="form-control" placeholder="Confirm Password" validate-equals='password' required>
<p class="help-block" ng-show="register.password_confirm.$dirty && register.password_confirm.$invalid">please match the password.</p>
<button ng-disabled="register.$invalid" class="btn btn-lg btn-primary btn-block" type="submit">
Submit
</button>
</form>
Front-end controller:
'use strict';
angular.module('app')
.controller('RegisterCtrl', function ($scope, $http, alert) {
$scope.submit = function() {
var url = 'http://localhost:3000/register';
var user = {
email: $scope.email,
password: $scope.password
};
$http.post(url, user)
.success(function(res){
alert('success', 'OK!', 'You are now registered');
})
.error(function(err) {
alert('warning', 'Opps!', 'Could not register');
});
}
});
Back-end NodeJS express server.
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(bodyParser.json());
//Verbind front-end met backend
app.use(function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
})
//MongoDB userModel
var User = mongoose.model('User', {
email: String,
password: String
});
//Reactie op de FRONT END POST voor REGISTRATIE
app.post('/register', function(req, res){
//emailVerification.s end(req.user.email);
//createSendToken(req.user, res);
var user = req.body;
console.log('req.body**' + req.body);
console.log('req.headers**' +req.headers);
var newUser = new User({
email: user.name,
password: user.password
})
newUser.save(function(err) {
//als goed opgeslagen > send status 200 en json new user
res.status(200).json(newUser);
console.log(newUser);
});
});
//MONGODB CONNECTIE =====================================
mongoose.connect('mongodb://....');
//MONGODB CONNECTIE =====================================
var server = app.listen(3000, function(){
console.log('api listening on ', server.address().port);
})
Thanks for your help.
Try using Dot operator , Change your Template as below,(sample code)
<form class="list" name="loginForm" ng-submit="login(credentials)" novalidate>
<label class="item item-input item-floating-label" for="username">
<span class="input-label">UserName</span>
<input type="text" placeholder="Username" id="username" ng-model="credentials.username">
</label>
<label class="item item-input item-floating-label" for="password">
<span class="input-label">Password</span>
<input type="password" placeholder="password" id="password" ng-model="credentials.password">
</label>
<button class="button button-block button-dark activated" type="submit">Logga in</button>
</form>
And in your Controller,
you get username as
var user = $scope.username;
Please read upon this article about Understanding Scopes
https://github.com/angular/angular.js/wiki/Understanding-Scopes#ngRepeat
Happy Coding
I made a typo in "Back-end NodeJS express server"
var newUser = new User({
email: **user.name,**
password: user.password
})
must be:
var newUser = new User({
email: **user.email,**
password: user.password
})
I am working through Ethan Brown's book "Web Development with Node and Express" and it has been going well until I got to enabling csrf the multipart/form-data upload on the photo upload. I downloaded the full book code from Github, https://github.com/EthanRBrown/web-development-with-node-and-express and that does the same thing, works until csrf is enabled then it errors with:
Error: invalid csrf token
here are the bits of code I think are relevant, /meadowlark.js starting at line 100
app.use(require('cookie-parser')(credentials.cookieSecret));
app.use(require('express-session')({ store: sessionStore,
secret: credentials.cookieSecret,
name: credentials.cookieName,
saveUninitialized: true,
resave: true }));
app.use(express.static(__dirname + '/public'));
app.use(require('body-parser')());
// cross-site request forgery protection
app.use(require('csurf')());
app.use(function(req, res, next){
res.locals._csrfToken = req.csrfToken();
next();
});
// database configuration
var mongoose = require('mongoose');
var options = {
server: {
socketOptions: { keepAlive: 1 }
}
};
Then in /handlers/contest.js
var path = require('path'),
fs = require('fs'),
formidable = require('formidable');
// make sure data directory exists
var dataDir = path.normalize(path.join(__dirname, '..', 'data'));
var vacationPhotoDir = path.join(dataDir, 'vacation-photo');
fs.existsSync(dataDir) || fs.mkdirSync(dataDir);
fs.existsSync(vacationPhotoDir) || fs.mkdirSync(vacationPhotoDir);
exports.vacationPhoto = function(req, res){
var now = new Date();
res.render('contest/vacation-photo', { year: now.getFullYear(), month: now.getMonth() });
};
function saveContestEntry(contestName, email, year, month, photoPath){
// TODO...this will come later
}
exports.vacationPhotoProcessPost = function(req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files){
if(err) return res.redirect(303, '/error');
if(err) {
res.session.flash = {
type: 'danger',
intro: 'Oops!',
message: 'There was an error processing your submission. ' +
'Pelase try again.',
};
return res.redirect(303, '/contest/vacation-photo');
}
var photo = files.photo;
var dir = vacationPhotoDir + '/' + Date.now();
var path = dir + '/' + photo.name;
fs.mkdirSync(dir);
fs.renameSync(photo.path, dir + '/' + photo.name);
saveContestEntry('vacation-photo', fields.email,
req.params.year, req.params.month, path);
req.session.flash = {
type: 'success',
intro: 'Good luck!',
message: 'You have been entered into the contest.',
};
return res.redirect(303, '/contest/vacation-photo/entries');
});
};
exports.vacationPhotoEntries = function(req, res){
res.render('contest/vacation-photo/entries');
};
and the views/contest/vacation-photo.handlebars
<form class="form-horizontal" role="form"
enctype="multipart/form-data" method="POST"
action="/contest/vacation-photo/{{year}}/{{month}}">
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
<div class="form-group">
<label for="fieldName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control"
id="fieldName" name="name">
</div>
</div>
<div class="form-group">
<label for="fieldEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" required
id="fieldName" name="email">
</div>
</div>
<div class="form-group">
<label for="fieldPhoto" class="col-sm-2 control-label">Vacation photo</label>
<div class="col-sm-4">
<input type="file" class="form-control" required accept="image/*"
id="fieldPhoto" data-url="/upload" name="photo">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
What is the proper way to make csrf work?
Thanks,
On vacation-photo GET request, you should send csrf token like below.
exports.vacationPhotoEntries = function(req, res){
res.render('contest/vacation-photo/entries', { _csrfToken: req.csrfToken()});
};
You can also catch csrf token error in your default error handler like below.
// error handler
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
// handle CSRF token errors here
res.status(403)
res.send('session has expired or form tampered with')
})
For more info, please check this link.
Append csrf token as query string to action Url..
It works!
<form class="form-horizontal" role="form" enctype="multipart/form-data" method="POST"
action="/contest/vacation-photo/{{year}}/{{month}}?_csrf={{_csrfToken}}">
</form>