req.body() is getting empty while inserting data in MERN - node.js

I have MERN project where i have to simply put my form data in my database. All looking good but data is not inserting. while there is no error also.
I have done console.log(req.body). after i getting empty {}.
As i have tried so many previous question in stackoverflow but noe of them helps me
this is my screenshot of console of my browser
Showing staus 201 but data is not going in my database
How to debug this error. I have tried all solution. Atleast tell me the possible reasons of this error. it will help me a lot. i am trying from full 1 day
userSchema
const userSchema = new mongoose.Schema({
identity: {
type: String,
},
names: {
type: String,
},
phone: {
type: String,
},
email: {
type: String,
},
city: {
type: String,
},
address: {
type: String,
},
subject: {
type: String,
},
classes: {
type: String,
},
message: {
type: String,
},
})
const USER = mongoose.model("USER", userSchema)
module.exports = USER
register.js(frontend)
const Register = () => {
const [newUser, setNewUser] = useState({
identity: "",
names: "",
phone: "",
email: "",
city: "",
address: "",
subject: "",
classes: "",
message: "",
});
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("identity", newUser.identity);
formData.append("names", newUser.names);
formData.append("phone", newUser.phone);
formData.append("email", newUser.email);
formData.append("city", newUser.city);
formData.append("address", newUser.address);
formData.append("subject", newUser.subject);
formData.append("classes", newUser.classes);
formData.append("message", newUser.message);
axios({
method: "post",
url: "/register",
data: formData,
headers: { "Content-Type": "application/json" },
})
.then((response) => {
console.log(response);
})
.then((data) => {
console.log(data);
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
}
});
};
const handleChange = (e) => {
setNewUser({ ...newUser, [e.target.name]: e.target.value });
};
return (
<>
<div class="container register mt-5">
<h1 class="well text-register shadow p-4 rounded-3">
Join as{" "}
<label class="student">
[{" "}
<img src="https://img.icons8.com/external-vitaliy-gorbachev-lineal-color-vitaly-gorbachev/60/000000/external-man-avatars-vitaliy-gorbachev-lineal-color-vitaly-gorbachev-12.png" />{" "}
Parent/Student{" "}
<img src="https://img.icons8.com/external-justicon-lineal-color-justicon/64/000000/external-student-back-to-school-justicon-lineal-color-justicon.png" />{" "}
]
</label>
<h1 class="well text-register down">
<i class="fas fa-arrow-right"></i> Hey! If you are looking for right
tutor near by your location. Don't worry you are at right place.{" "}
<i class="fas fa-arrow-left"></i>
</h1>
</h1>
<div class="col-lg-12 well rounded-3">
<div class="row mt-5 ">
<form onSubmit={handleSubmit} method = "post" class="shadow p-5">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Your Identity
</label>
<input
type="text"
placeholder="Write Student or Parent"
class="form-control"
name="identity"
id="identity"
value={newUser.identity}
onChange={handleChange}
/>
</div>
</div>
<div class="form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Name
</label>
<input
type="text"
placeholder="Enter Your Full Name Here.."
class="form-control"
name="names"
id="names"
value={newUser.names}
onChange={handleChange}
/>
</div>
<div class="form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Phone Number
</label>
<input
type="text"
placeholder="Enter Phone Number Here.."
class="form-control"
name="phone"
id="phone"
value={newUser.phone}
onChange={handleChange}
/>
</div>
<div class="form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Email Address
</label>
<input
type="text"
placeholder="Enter Email Address Here.."
class="form-control"
name="email"
id="email"
value={newUser.email}
onChange={handleChange}
/>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> City
</label>
<input
type="text"
placeholder="Enter City Name Here.."
class="form-control"
name="city"
id="city"
value={newUser.city}
onChange={handleChange}
/>
</div>
<div class="col-sm-6 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Address
</label>
<textarea
placeholder="Enter Address Here.."
rows="3"
class="form-control"
name="address"
id="address"
value={newUser.address}
onChange={handleChange}
></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Subject
</label>
<input
type="text"
placeholder="Enter Subject Here.."
class="form-control"
name="subject"
id="subject"
value={newUser.subject}
onChange={handleChange}
/>
</div>
<div class="col-sm-6 form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i>Student Class
</label>
<input
type="text"
placeholder="Enter Student Class"
class="form-control"
name="classes"
id="classes"
value={newUser.classes}
onChange={handleChange}
/>
</div>
</div>
<div class="form-group">
<label>
{" "}
<i class="far fa-dot-circle"></i> Message
</label>
<textarea
placeholder="Enter Any message you have for us..."
rows="3"
class="form-control"
name="message"
id="message"
value={newUser.message}
onChange={handleChange}
></textarea>
</div>
<button value="register" type="submit" class="btn btn-lg btn-info">
Submit
</button>
</div>
</form>
</div>
</div>
</div>
</>
);
};
auth.js
router.get("/", (req, res) => {
res.send("hello, i am communicating with router");
})
router.post("/register", async (req, res) => {
const { identity, names, phone, email, city, address, subject, classes, message } = req.body
console.log(req.body)
try {
const user = new User({identity ,names, phone,email,city,address, subject, classes, message })
await user.save()
res.status(201).json({ message: "user registered successfulluy" })
} catch (err) {
console.log(err)
}
})
module.exports = router
app.js
const port = 5000
env.config({path: "../server/config.env"})
require("../server/db/conn")
app.use(cors());
app.use(express.json())
app.use(require("../server/router/Auth"))
app.listen(port, (err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
Please help. i have tried so many times!!
Thankyou!!!

Modify Your HandleSubmit function, do not use formData to submit your data as application/json
Instead, just use your current React State
const handleSubmit = (e) => {
e.preventDefault();
axios({
method: "post",
url: "/register",
data: JSON.stringify(newUser),
headers: { "Content-Type": "application/json" },
})
.then((response) => {
console.log(response);
})
.then((data) => {
console.log(data);
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
}
});
};

Related

when i try to post new product from localhost get error message

Here is my Post API working greet with postman
router.post(`/`, uploadOptions.single('image'), async (req, res) =>{
const category = await Category.findById(req.body.category);
if(!category) return res.status(400).send('Invalid Category')
const file = req.file;
if(!file) return res.status(400).send('No image in the request')
const fileName = req.file.filename
const basePath = `${req.protocol}://${req.get('host')}/public/uploads/`;
let product = new Product({
name: req.body.name,
description: req.body.description,
richDescription: req.body.richDescription,
image: `${basePath}${fileName}`,
brand: req.body.brand,
price: req.body.price,
category: req.body.category,
countInStock: req.body.countInStock,
rating: req.body.rating,
numReviews: req.body.numReviews,
isFeatured: req.body.isFeatured,
})
product = await product.save();
if(!product)
return res.status(500).send('The product cannont be created')
res.send(product);
})
and this my form
<div class="container">
<div class="fadein">
<h2 class="page-header">add new product </h2>
<!-- <div class="alert alert-danger" *ngIf="" role="alert"></div> -->
<form #addProductForm="ngForm" (ngSubmit)="SubmitData(addProductForm)">
<div class="form-group">
<label for="name">Name
<sup class="red">*</sup>
</label>
<input required name="name" id="name" #name="ngModel" ngModel type="text" class="form-control">
</div>
<div class="form-group">
<label for="description">description
<sup class="red">*</sup>
</label>
<input required name="description" id="description" #description="ngModel" ngModel type="text" class="form-control">
</div>
<div class="form-group">
<label for="richDescription">richDescription
<sup class="red">*</sup>
</label>
<input required name="richDescription" id="richDescription" #richDescription="ngModel" ngModel type="text" class="form-control">
</div>
<div class="form-group">
<label for="brand">brand
<sup class="red">*</sup>
</label>
<input required name="brand" id="brand" #brand="ngModel" ngModel type="text" class="form-control">
</div>
<div class="form-group">
<label for="price">price
<sup class="red">*</sup>
</label>
<input required name="price" id="price" #price="ngModel" ngModel type="number" class="form-control">
</div>
<div class="form-group">
<label for="category">category
<sup class="red">*</sup>
</label>
<input required name="category" id="category" #category="ngModel" ngModel type="text" class="form-control">
</div>
<div class="form-group">
<label for="countInStock">countInStock
<sup class="red">*</sup>
</label>
<input required name="countInStock" id="countInStock" #countInStock="ngModel" ngModel type="number" class="form-control">
</div>
<div class="form-group">
<label for="image">image
<sup class="red">*</sup>
</label>
<input required type="file" name="file" #file="ngModel" [ngModel] accept="image/*">
</div>
<br>
<input type="submit" class="btn btn-primary" value="Add Product" [disabled]="!addProductForm.valid">
</form>
</div>
</div>
and this from component
SubmitData(form: { value: {
category: string; name: string; description: string; brand: string; richDescription: string;
price: number; countInStock: number; image: File;
}; }){
const data = {
name: form.value.name,
description: form.value.description,
richDescription: form.value.richDescription,
brand: form.value.brand,
price: form.value.price,
category: form.value.category,
countInStock: form.value.countInStock,
image: form.value.image,
};
this.productService.postData(data).subscribe(response => {
console.log(response);
});
}
product Services
import { HttpClient, HttpHeaders , HttpEvent} from "#angular/common/http";
import { Injectable } from '#angular/core';
import { Product } from "../models/Product";
import { map, Observable, switchMap, tap } from "rxjs";
#Injectable({
providedIn: 'root'
})
export class ProductService {
// jsonURL = 'assets/data.json';
warehouseURL = 'http://localhost:5000/v1/products/';
constructor(private http: HttpClient) { }
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.warehouseURL)
.pipe(
tap(data => console.log('All: ', JSON.stringify(data))),
);
}
getProduct(_id: string): Observable<Product | any> {
return this.getProducts()
.pipe(
map((products: Product[]) => products.find(p => p._id === _id)
)
)
}
RemoveProduct(_id: string){
this.http.delete<Product[]>(this.warehouseURL+ _id)
.subscribe(()=>{
})
}
postData(data: any): Observable<any>{
return this.http.post(`${this.warehouseURL}`, data)
.pipe(
tap(data => console.log('All: ', JSON.stringify(data))),
);
}
}
when I try to post using postman it works fine, but I cannot post data from the application it self and generates an error message "400 NO image in the request".So can you guys tell me what my mistake is? thank you very much!
Change image input tag's name attribute to image instead of file, and also, you need to add file listener, and include it to the form upon submit:
<input type="file" name="image" #image="ngModel" [ngModel] accept="image/*" (change)="onFileChange($event)">
Also, you need to prepare form-data and send that instead of an object.
// file holder
image?: File | any;
// file listener
onFileChange(event: any) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.image = file
}
}
construct form in the SubmitData:
const data = new FormData();
data.append('name', form.value.name);
data.append('description', form.value.description);
data.append('richDescription', form.value.richDescription);
data.append('brand', form.value.brand);
data.append('price', form.value.price);
data.append('category', form.value.category);
data.append('countInStock', form.value.countInStock);
data.append('image', this.image);

How to check if a username is taken in Mongo Schema with an AJAX API call

I am trying to create a registration form where a potential user is typing in their desired username it checks against the existing Mongo DB User Schema to see if that exact name exists.
The form I have is here:
<form class="needs-validation" action="/register" method="POST" novalidate>
<div class="text-center mb-3">
<p class="lead">Welcome to the team! We just need a few things to get started.</p>
<div class="row">
<div class="col-md-6 mb-4">
<div class="form-outline">
<input
type="text"
id="first_name"
name="first_name"
class="form-control"
required
/>
<label class="form-label" for="first_name"
>First name</label
>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Thats not right</div>
</div>
</div>
<div class="col-md-6 mb-4">
<div class="form-outline">
<input
type="text"
id="last-name"
name="last-name"
class="form-control"
required
/>
<label class="form-label" for="last-name"
>Last name</label
>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Thats not right</div>
</div>
</div>
</div>
<!-- Email input -->
<div class="form-outline mb-4">
<input
type="email"
id="register_email"
name="register_email"
class="form-control"
required
/>
<label class="form-label" for="register_email">Email</label>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Thats not right</div>
</div>
<div class="text-center mb-3">
<div class="form-outline mb-4">
<input type="text" id="register_username" name="register_username" class="form-control" placeholder="enter your username" required />
<label class="form-label" for="register_username">Username</label>
<div id="username-check"></div>
</div>
<!-- Password input -->
<div class="form-outline mb-4">
<input type="password" id="register_password" name="register_password" class="form-control" required/>
<label class="form-label" for="register_password">Password</label>
</div>
</div>
<!-- Submit button -->
<div class="text-center">
<button type="submit" id="register" class="btn btn-lg btn-rounded bg-insider link-dark mb-3 fw-bold" disabled>
Lets Go! <i class="fa-solid fa-gauge-max"></i>
</button>
</div>
</form>
I have this script code working on the page to take the user input and check to a get route that should be checking my MongoDB:
$('#register_username').on('keyup', function () {
$.get('/usercheck?username=' + $(this).val().toLowerCase(), function (response) {
$('#username-check').text(response.message);
console.log('')
var btn = document.getElementById('register');
btn.disabled = true;
if ($('#username-check').html() === "user exists") {
$('#username-check').text('username not available').css('color', 'red');
}
else {
console.log($('#register_username').val())
$('#username-check').text('username is available').css('color', 'green');
btn.disabled = false;
}
})
});
This is the route it calls to check the database:
var express = require("express"),
router = express.Router(),
passport = require("passport"),
User = require("../models/user");
router.get('/usercheck', function(req, res) {
console.log(req.query);
User.findOne({username: req.query.register_username}, function(err, username){
if(err) {
console.log(err);
}
var message;
if(username) {
console.log(username);
message = "user exists";
console.log(message);
} else {
message= "user doesn't exist";
console.log(message);
}
res.json({message: message});
});
});
module.exports = router;
In case this helps, this is the user Schema in the database:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
isAdmin: { type: Boolean, default: false }
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User",UserSchema);
I am not sure what I am missing but anything would be extremely helpful. Thanks in advance!
Just so this question can be closed successfully:
Changing /usercheck?username= to /usercheck?register_username= did the trick, because this query param was used in the form:
$('#register_username').on('keyup', function () {
$.get('/usercheck?register_username=' + $(this).val().toLowerCase(), function (response) {
$('#username-check').text(response.message);
console.log('')
var btn = document.getElementById('register');
btn.disabled = true;
if ($('#username-check').html() === "user exists") {
$('#username-check').text('username not available').css('color', 'red');
}
else {
console.log($('#register_username').val())
$('#username-check').text('username is available').css('color', 'green');
btn.disabled = false;
}
})
});

using React can I prevent sending empty strings from my inputs to my mongodb database during update?

I have inputs that take in information that is set to the state. The states initial values is set to empty strings. none of the inputs are required inputs so some may remain blank I then send the inputted information to the the API but that may send possible empty strings which would replaces information that I don't want to update.
I tried setting the initial states to undefined but i got the uncontrolled inputs error because I know undefined values would not be accepted in my database.
I have thought about maybe creating an array and pushing only the values that aren't equal to an empty string into it and then sending the array to the API.
import React from "react";
import API from "../../utils/API";
import { Link } from "react-router-dom";
import { storage } from "../../config/fire";
class ProfileEditor extends React.Component {
state = {
image: null,
url: "",
isActive: false,
emailaddress: "",
password: "",
confirm: "",
screenName: "",
securityQuestion: "",
securityAnswer: "",
birthDate: "",
gender: "",
phoneNumber: "",
cityState: "",
userPic: "",
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
updateProfile = id => {
if (this.state.password.length > 0 && this.state.password.length < 6) {
alert(
`Choose a more secure password `
);
} else if (this.state.password !== this.state.confirm) {
alert("You Passwords do not match");
} else {
API.updateEditProfile(id, {
password: this.state.password,
screenName: this.state.screenName,
securityQuestion: this.state.securityQuestion,
securityAnswer: this.state.securityAnswer,
birthDate: this.state.birthDate,
gender: this.state.gender,
phoneNumber: this.state.phoneNumber,
cityState: this.state.cityState,
userPic: this.state.url
})
.then(function (response) {
console.log(response);
})
.catch(err => console.log(err));
document.getElementById("profileForm").reset();
}
}
handleImageSelected = event => {
this.uploadClick()
if (event.target.files[0]) {
const image = event.target.files[0];
this.setState(() => ({ image }));
}
}
handleUpload = () => {
const fullName = this.props.userInfo.firstname + "_" + this.props.userInfo.lastname;
const { image } = this.state;
const uploadTask = storage.ref(fullName + "/" + image.name).put(image);
uploadTask.on("state_changed",
(snapshot) => {
const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
this.setState({ progress: progress })
},
(error) => {
console.log(error);
},
() => {
storage.ref(fullName).child(image.name).getDownloadURL()
.then(url => {
this.setState({ url: url });
console.log(url)
})
});
}
uploadClick = () => {
this.setState({ isActive: !this.state.isActive })
};
render() {
const fullName = this.props.userInfo.firstname + " " + this.props.userInfo.lastname
const user = this.props.userInfo
console.log(this.props.userInfo.userPic)
return (
<div className="contentArea ">
<div className="profile-container">
<div className="profile-image">
<img src={this.props.userInfo.userPic} />
</div>
<div className="profile-info">
{fullName}
</div>
<section className="editProfile">
<div className="unchangeable">Name: {fullName} </div>
<div className="unchangeable">Email: {this.props.userInfo.emailaddress}</div>
<form id="profileForm">
<div className="profileInputs">
<input value={this.state.password} onChange={this.handleChange} type="password" placeholder="Password" name="password" ref="password" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.confirm} onChange={this.handleChange} type="password" placeholder="confirm password" name="confirm" ref="confirmPassword" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.securityQuestion} onChange={this.handleChange} type="text" placeholder="security question" name="securityQuestion" ref="securityQuestion" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.securityAnswer} onChange={this.handleChange} type="text" placeholder="Answer to security question" name="securityAnswer" ref="securityAnswer" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.screenName} onChange={this.handleChange} placeholder="screen name" name="screenName" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.birthDate} onChange={this.handleChange} type="text" placeholder="birth date" name="birthDate" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.Gender} onChange={this.handleChange} type="text" placeholder="gender" name="gender" className=" editInput" />
</div>
<div className="profileInputs">
<input value={this.state.phoneNumber} onChange={this.handleChange} type="text" placeholder="phone number" name="phoneNumber" className=" editInput" />
</div>
<div className="profileInputs">
<input value={this.state.cityState} onChange={this.handleChange} type="text" placeholder="city/state" name="cityState" className=" editInput" />
</div>
<div className="profileInputs"> Are you in a Relationship?
<input value={this.state.Gender} onChange={this.handleChange} type="text" placeholder="" name="gender" className=" editInput" />
</div>
</form>
</section>
<section className="feed ">
<div className="avatar">
<div className="avatarsect">
Upload Avatar
</div>
<input type="file" style={{ display: "none" }} onChange={this.handleImageSelected} ref={fileInput => this.fileInput = fileInput} />
<img className={this.state.isActive ? "uploadReady active" : "uploadReady"} src={this.state.url} alt="previewupload" height="40" width="50" />
<progress className={this.state.isActive ? "uploadReady active" : "uploadReady"} value={this.state.progress} max="100" />
<button className={this.state.isActive ? "uploadReady active" : "uploadReady"} onClick={this.handleUpload}>Upload</button>
<span className={this.state.isActive ? "uploadReady active" : "uploadReady"}></span>
<button type="button" className="button photo" onClick={() => this.fileInput.click()}><i class="fas fa-camera-retro"></i></button>
</div>
<br></br>
<br></br>
<div className="btnDiv">
<button onClick={() => this.updateProfile(this.props.userInfo.user_ID)} className="updateProfileBtn"> Update Profile</button>
</div>
<br></br>
<br></br>
<br></br>
<br></br>
</section>
</div>
</div>
);
}
}
export default ProfileEditor;
my Api
updateEditProfile:function(id,userData) {
console.log(userData)
console.log(id)
return axios.put("/api/usersData/" +id, userData);
},
my route and controller
router.route("/")
.post(usersDataController.findUserinfo)
.put(usersDataController.update)
router.route("/:id")
.put(usersDataController.updateByID);
updateByID: function(req, res) {
console.log(res)
db.usersData
.findByIdAndUpdate({ _id: req.params.id }, req.body,{new:true})
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},

React, Node: Variable shows undefined on app.post()

Not sure if I've done it correctly on the server or client side, but in the client side when I console.log(values) they appear, but in server, I get undefined. But when i do enter the right credentials for a user in the database i get status:ok, so something is found. And also a extra bug is i cannot to the post request twice, then i get the error: Error: Cannot enqueue Handshake after invoking quit.
Client Code:
class Login extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
const email = data.get('email');
const password = data.get('password');
fetch('/authentication', {
method: 'POST',
body: JSON.stringify({
"email": email,
"password": password
}),
}).then(function (response) {
if (response.ok) {
alert("Login Successful!");
} else {
console.log("Failed");
}
});
console.log("Email: " + email);
console.log("pwd: " + password);
}
render() {
return (
<form className="col s12 m12 l12" onSubmit={this.handleSubmit}>
<div className="row">
<div className="col s12 center-align">
<img className="logo" src="images/bibdata-center.png" alt="BibData Logo"/>
</div>
<div className="input-field col s12">
<i className="material-icons prefix">email</i>
<input id="email" name="email" type="email" className="validate" onChange={this.handleEmailChange}/>
<label htmlFor="email">Email</label>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<i className="material-icons prefix">lock</i>
<input id="password" name="password" type="password" className="validate" onChange={this.handlePasswordChange}/>
<label htmlFor="password">Password</label>
</div>
</div>
<div className="row">
<div className="col s12 m6 l6 center-align">
<button className="btn waves-effect btn-large waves-light" type="submit" value="Submit" name="action">Sign in
<i className="material-icons right">send</i>
</button>
</div>
<div className="col s12 m6 l6 center-align">
<button className="btn waves-effect btn-large waves-light blue" type="submit" name="action"
onClick={() => renderReactComponent(newUser, 'root')}>
Register
</button>
</div>
</div>
<div className="row">
<div className="col s12 center-align">
<a href="#" onClick={() => renderReactComponent(forgotPassword, 'root')}>
<span className="helper-text grey-text text-darken-1"
data-error="wrong" data-success="right">
Forgot password?
</span>
</a>
</div>
</div>
</form>
);
}
}
And Server Code:
app.post('/authentication', function (req, res) {
connection.connect();
let email = req.body.email;
let password = req.body.password;
console.log(email);
console.log(password);
connection.query('SELECT * FROM user WHERE email = ? AND password = ?',
[email, password], function (error, results, fields) {
if (error) {
return res.status(500).send(error);
}
return res.send({ error: false, data: results, message: 'ok'})
});
connection.end();
});
All help will be appreciated!
When you make your fetch call to /authentication endpoint, you are sending serialized JSON data in your request body. The server however has no means of knowing that you have actually sent an JSON. When posting JSON, you must indicate that by providing appropriate content-type header.
In this case your fetch options (2nd param) should have one more property like this:
...
headers: {
"Content-Type": "application/json",
},
...
This is assuming, you have already setup body-parser or another similar module on your server side code which can parse JSON request body.

Insert in bulk using Sequelize with Node and Express

Looking for a way to insert activities to the database in bulk using Sequelize Model.bulkCreate.
Not sure how to bring the activities from the view to the route function in order to insert them using bulkCreate. Right now I only insert one activity.
View:
<form action="/create" method="POST">
<div class="form-group">
<label>Plan Name</label>
<input type="text" name="plan_name" placeholder="Plan Name">
</div>
<div class="form-group">
<label>Description</label>
<input type="text" name="description" placeholder="Description">
</div>
<div class="form-group">
<label>Activity</label>
<input type="text" name="activity_name" placeholder="Activity">
<label>Comment</label>
<input type="text" name="comment" placeholder="Comment">
<input type="button" id="add" class="btn btn-success" value="Add">
</div>
<div class="form-group" id="new">
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<input type="submit" class="btn btn-success" value="Submit">
</form>
<script type="text/javascript">
$('#add').click(function() {
let activity = $('<div class="form-group"><label>Activity</label><input type="text" name="activity_name" placeholder="Activity"><label>Comment</label><input type="text" name="comment" placeholder="Comment"></div>');
$('#new').append(activity);
});
</script>
Route:
app.post('/create', (req, res) => {
const user_id = req.user.id;
const data = {
plan_name: req.body.plan_name,
description: req.body.description,
userId: user_id
};
PlanModel.Plan.create(data).then(plan => {
const activity = {
activity_name: req.body.activity_name,
comment: req.body.comment,
plans_id: plan.id
};
ActivityModel.Activity.create(activity);
res.redirect('/');
});
});
1) Make fields to have names like an array
<div class="activities">
<div class="form-group">
<label>Activity</label>
<input type="text" name="activities[0][name]" placeholder="Activity">
<label>Comment</label>
<input type="text" name="activities[0][comment]" placeholder="Comment">
</div>
<div class="form-group">
<label>Activity</label>
<input type="text" name="activities[1][name]" placeholder="Activity">
<label>Comment</label>
<input type="text" name="activities[1][comment]" placeholder="Comment">
</div>
</div>
<div class="form-group>
<input type="button" id="add" class="btn btn-success" value="Add">
</div>
2) At server-side just take that req.body.activities and generate array of objects and call bulkCreate
app.post('/create', async (req, res) => {
try {
const data = {
plan_name: req.body.plan_name,
description: req.body.description,
userId: req.user.id
};
const plan = await PlanModel.Plan.create(data);
if (req.body.activities && Array.isArray(req.body.activities)) {
const activities = req.body.activities.map(
activity => {
return {
activity_name: activity.name,
comment: activity.comment,
plans_id: plan.id
}
});
await ActivityModel.Activity.bulkCreate(activities);
}
res.redirect('/');
}
catch(error) {
res.status(500).send(error);
}
});
3) Since body parser for urlencoded mode has extended option that parses deeply all of the fields. You've to enable it.
MAKE SURE that bodyParser middleware attached with extended: true :
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

Resources