User validation failed: password: Path `password` is required - node.js

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

Related

Cookie error in node.JS app with next.js client program

I am actually write a node.JS application on natours project. It is actually a course project that was designed by jonas. I am designing a next.JS client side program of this backend program. Problem was that when I submit a request on http://localhost:3000/api/v1/users/signup url everything is ok, cookie is set but when I send a request on others url on this server like http://localhost:3000/api/v1/tours cookie is not read by the server and req.cookies is null. I am trying to solve this problem but I am stuck.
app.js Code
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const rateLimit = require("express-rate-limit");
const helmet = require("helmet");
const xss = require("xss-clean");
const mongoSanitize = require("express-mongo-sanitize");
const hpp = require("hpp");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const globalErrorHandler = require("./controllers/errorController");
const tourRouter = require("./routes/tourRoutes");
const userRouter = require("./routes/userRoutes");
const reviewRouter = require("./routes/reviewRoutes");
const AppError = require("./utils/appError");
const app = express();
app.set("view engine", "pug");
app.set("views", `${__dirname}/views`);
// GLOBAL MIDDLEWARE
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"));
}
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: "Too many requests from this IP, Please try again in an hour.",
});
app.use(cors({ credentials: true, origin: "http://localhost:3001" }));
app.use(helmet());
app.use(xss());
app.use("/api", limiter);
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: "10kb" }));
app.use(express.static(`${__dirname}/public`));
app.use(mongoSanitize());
app.use(
hpp({
whitelist: [
"duration",
"ratingsQuantiry",
"ratingsAverage",
"difficulty",
"maxGroupSize",
"price",
],
})
);
app.use((req, res, next) => {
req.requestTime = Date.now();
console.log(req.cookies.jwt);
next();
});
app.get("/", (req, res) => {
res.status(200).render("base", {
title: "Natours",
});
});
app.use("/api/v1/tours", tourRouter);
app.use("/api/v1/users", userRouter);
app.use("/api/v1/reviews", reviewRouter);
app.all("*", (req, res, next) => {
// res.status(404).json({
// status: "fail",
// message: `Can't find ${req.originalUrl} on ther server.`,
// });
const err = new AppError(
`Can't find ${req.originalUrl} on ther server.`,
404
);
next(err);
});
app.use(globalErrorHandler);
module.exports = app;
Client Code in Next.js
import React, { useState } from "react";
import axios from "axios";
import Layout from "../components/Layout";
const url = "http://localhost:3000/api/v1/users/signup";
const styles = {
"input-group": "flex flex-col gap-3",
"input-label": "px-2 text-md font-thin",
"text-input": "px-2 py-4",
button:
"px-4 py-3 font-thin uppercase text-md bg-teal-700 hover:bg-teal-600 text-slate-50 rounded-sm",
"cancle-button": "bg-red-700 hover:bg-red-600",
};
function Register() {
const [formData, setFormData] = useState({
name: "",
email: "",
password: "",
passwordConfirm: "",
photo: "",
});
const handleChange = (event) => {
setFormData({
...formData,
[event.target.name]: event.target.value,
});
};
const handleSubmit = async (event) => {
event.preventDefault();
axios
.post("http://localhost:3000/api/v1/users/signup", formData, {
withCredentials: true,
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
alert(JSON.stringify(formData));
};
const handleReset = (event) => {
setFormData({
name: "",
email: "",
password: "",
passwordConfirm: "",
photo: "",
});
};
return (
<Layout>
<div className="p-10 bg-slate-50">
<form onSubmit={handleSubmit}>
<h1 className="text-2xl mb-5 text-teal-700">Register your account</h1>
<div className="w-1/2 flex flex-col gap-3">
<div className={styles["input-group"]}>
<label className={styles["input-label"]}>Name</label>
<input
className={styles["text-input"]}
placeholder="Enter your name"
type="text"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
<div className={styles["input-group"]}>
<label className={styles["input-label"]}>Email</label>
<input
className={styles["text-input"]}
placeholder="Enter your email"
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<div className={styles["input-group"]}>
<label className={styles["input-label"]}>Password</label>
<input
className={styles["text-input"]}
placeholder="Enter your password"
type="password"
name="password"
value={formData.password}
onChange={handleChange}
required
/>
</div>
<div className={styles["input-group"]}>
<label className={styles["input-label"]}>Confirm Password</label>
<input
className={styles["text-input"]}
placeholder="Enter your confirm password"
type="password"
name="passwordConfirm"
value={formData.passwordConfirm}
onChange={handleChange}
required
/>
</div>
</div>
<div className="bg-slate-100 flex gap-3 mt-5 px-3 py-6 w-1/2">
<button className={styles.button} type="submit">
Register
</button>
<button
className={`${styles.button} ${styles["cancle-button"]}`}
type="reset"
onClick={handleReset}
>
Cancle
</button>
</div>
</form>
</div>
</Layout>
);
}
export default Register;

How to find whether user has signed up before login, in react, node and mariadb

I am new to react and mariaDB and this is my first attempt. I have created a sign up and sign in form in a single page. I used reactjs for frontend and node for backend and used mariaDB as database. I was able to insert username and password to databse when sign up. Now I want to check whether user has signed up when user try to login. I want to display an error as Wrong combination when username and password is not matched with registered users. I tried to display it, but it doesn't work.
here is my app.js in client side ,
import React, { useState } from 'react';
import './App.css';
import Axios from "axios";
function App() {
const [usernameReg,setUsernameReg]= useState("");
const [passwordReg,setPasswordReg]= useState("");
const [username,setUsername]= useState("");
const [password,setPassword]= useState("");
const [loginStatus,setLoginStatus]= useState("");
const register = () => {
Axios.post("http://localhost:3001/register", {
username:usernameReg,
password:passwordReg,
}).then((response) => {
console.log(response);
});
};
const login = () => {
Axios.post("http://localhost:3001/login", {
username:username,
password:password,
}).then((response) => {
if(response.data.message){
setLoginStatus(response.data.message);
}
else{
setLoginStatus(response.data[0].username);
}
});
};
return (
<div className="App">
<div className='registration'>
<label>Username</label>
<br/>
<input type="text" onChange={(e)=>{
setUsernameReg(e.target.value)
}}>
</input>
<br/>
<label>Password</label>
<br/>
<input type="text" onChange={(e)=>{
setPasswordReg(e.target.value)
}}>
</input>
<br/>
<button onClick={register}>Register</button>
<br/>
</div>
<div className='login'>
<br/>
<label>Username</label>
<br/>
<input type="text"
onChange={(e)=>{
setUsername(e.target.value)
}}
></input>
<br/>
<label>Password</label>
<br/>
<input type="text"
onChange={(e)=>{
setPassword(e.target.value)
}}
></input>
<br/>
<button onClick={login}>Login</button>
</div>
<h1>{loginStatus}</h1>
</div>
);
}
export default App;
here is my index.js in server side
const express = require("express");
const mariadb = require("mariadb");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json());
const db = mariadb.createPool({
user: "root",
host: "localhost",
password: "NishR",
database: "pedro",
});
app.post("/register", async (req, res) => {
const username= req.body.username;
const password = req.body.password;
db.query(
"INSERT INTO user (username,PASSWORD) VALUES(?,?)",
[username,password],
(err,result)=>{
console.log(err);
}
);
}
);
app.post("/login", async (req, res) => {
const username= req.body.username;
const password = req.body.password;
db.query(
"SELECT * FROM user WHERE username=? AND password=?",
[username,password],
(err,result)=>{
if (err){
res.send({err:err});
}
if(result.length>0){
res.send(result);
}else{
res.send({message:"wrong combination"});
}
}
);
}
);
app.listen(3001, () => {
console.log("Server is running");
});
please help me to find the error.

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!

req.body always empty when sending form via frontend

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

bodyparser issue NodeJS express POST >" email undefined"

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

Resources