I want to send form data including a file to my express API for adding churches in my database and i want to upload church details and an image for this.
this is my HTML form :
<form action="" id="ad-bis">
<div class="form-group">
<label>INTRODU NUMEle BISERICII</label>
<input
type="text"
name="biserica"
id="biserica"
class="form-control"
/>
<span id="error_biserica" class="text-danger"></span>
</div>
<div class="form-group">
<label>INTRODU ORASUL</label>
<input type="text" name="oras" id="oras" class="form-control" />
<span id="error_oras" class="text-danger"></span>
</div>
<div class="form-group">
<label>INTRODU ADRESA</label>
<input type="text" name="adresa" id="adresa" class="form-control" />
<span id="error_adresa" class="text-danger"></span>
</div>
<div class="form-group">
<label>INTRODU NUME PREOT</label>
<input type="text" name="preot" id="preot" class="form-control" />
<span id="error_preot" class="text-danger"></span>
</div>
<div class="form-group">
<label for="poza">ADAUGA POZA</label>
<input type="file" id="poza" />
</div>
<div class="form-group" align="center">
<button type="submit" name="save" id="save" class="btn btn-info">
SALVARE
</button>
</div>
</form>
in my js file i created submit function:
adBis.addEventListener("submit", async e => {
e.preventDefault();
const data = new FormData();
data.append(
"data",
JSON.stringify({
nume: document.querySelector("#biserica").value,
oras: document.querySelector("#oras").value,
adresa: document.querySelector("#adresa").value,
preot: document.querySelector("#preot").value,
uid: localStorage.getItem("uid")
})
);
data.append("poza", _("#poza").files[0]);
console.log(data);
const res = await await fetch("http://localhost:8080/api/site/adaugare", {
method: "POST",
body: data
});
const serverData = await res.json();
console.log(res, serverData);
_(".info").style.display = "none";
if (!serverData.success) {
afisareEroare(data.msg);
}
console.log("ok");
await afisRezultate(localStorage.getItem("uid"));
});
then i created endpoint in express using multer tu upload file:
const multer = require("multer");
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "../images");
},
filename: function(req, file, cb) {
cb(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
const upload = multer({
storage: storage
}).array("imgUploader", 3);
outer.post("/adaugare", (req, res) => {
console.log(req.body);
res.json({ msg: "ok" });
/*
*/
});
in my console, req.body is empty how send all data?
I tried with firebase storage but it doesn't work for me.
what I missed?
thanks!
First tip: Since you are using FormData you can pass the form in to get automatically all the values in the form.
Second, here you are awaiting twice:
const res = await await fetch("http://localhost:8080/api/site/adaugare", [...]
Lastly req.body empty is either because of lack of body-parser or, as I see here, you have not added the enctype="multipart/form-data" attribute, without this Multer won't get any data from your form.
Related
I'm trying to learn express/nodejs and implement a form, where after recaptcha you can click and download a file. But after form submission I'm being redirected to localhost/submit with only status code on the page. This is driving me crazy, I just want to enable download button after passing recaptcha. I believe this is obvious, but not for me.
server.js file
// Load Node modules
var express = require("express");
const fetch = require("isomorphic-fetch");
// Initialise Express
var app = express();
// Render static files
app.use(express.static("public"));
// Port website will run on
app.listen(8080);
// To accept HTML form data
app.use(express.urlencoded({ extended: false }));
// Here, HTML form is submit
app.post("/submit", (req, res) => {
const name = req.body.name;
// getting site key from client side
const response_key = req.body["g-recaptcha-response"];
// Put secret key here, which we get from google console
const secret_key = "6LdGoQohAAAAAJe6wa_-xayew_ht3N6Lm-kSdbW9";
console.log(res);
// Hitting POST request to the URL, Google will
// respond with success or error scenario.
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${response_key}`;
// Making POST request to verify captcha
fetch(url, {
method: "post",
})
.then((response) => response.json())
.then((google_response) => {
// google_response is the object return by
// google as a response
if (google_response.success == true) {
// if captcha is verified
return res.sendStatus(200);
} else {
// if captcha is not verified
console.log(google_response);
return res.sendStatus(400);
}
})
.catch((error) => {
// Some error while verify captcha
return res.json({ error });
});
});
html form
<form class="main-form" action="/submit" method="post" id="myForm">
<div class="form-row">
<div class="form-element">
<label for="form-delivery">Номер поставки:</label>
<input type="text" name="delivery" required id="form-delivery" />
</div>
<div class="form-element">
<label for="form-num">Номер ТТН:</label>
<input type="text" name="delivery2" id="form-num" />
</div>
</div>
<div class="form-row">
<div class="form-element">
<label for="form-date" req>Дата формирования:</label>
<input type="date" name="delivery3" id="form-date" required />
</div>
<div class="form-element">
<label for="form-client">Клиент:</label>
<input type="text" name="delivery4" id="form-client" />
</div>
</div>
<div class="form-row">
<div class="form-element">
<label for="form-car">Гос. номер:</label>
<input type="text" name="delivery5" id="form-car" />
</div>
<div class="form-element">
<label for="form-cert">Номер сертификата:</label>
<input type="text" name="delivery6" id="form-cert" />
</div>
</div>
<div id="g"></div>
<button class="download-link" type="submit">Скачать</button>
</form>
So I am following a YouTube Tutorial on how to set up a simple login server (channel name: web dev simplified, video: "Node.js Passport Login System Tutorial")
The code (at the stage I am at # 14:12 mark in video) is suppose to console-log an array of a new registered user at the terminal.
but I get an empty array instead. Despite having the same code (I followed him step by step) I do not get the new user. What am I doing wrong?
const path = require('path');
const fs = require('fs');
const express = require('express');
const app= express();
const bcrypt = require('bcrypt');
const session = require('express-session');
// Get express ready to setup server
var users =[];
//{id:"", name:"", email:"", password:"",}
app.set('view-engine', 'ejs')
app.use(express.urlencoded({ extended: false }));
// Sets up main page
app.get('/', (req, res) => {
res.render('index.ejs', {name: 'Moe'})
})
////////////////Sets up login page////////////////////////
app.get('/login', (req, res) => {
res.render('login.ejs')
})
///////////////Sets up register page////////////////////////
app.get('/register', (req, res) => {
res.render('register.ejs')
})
///////////////////// Recieves date from register /////////////////
app.post('/register', async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
users.push({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
res.redirect('/login')
} catch {
res.redirect('/register')
}
console.log(users);
});
///////////////////////////////////////////////////////
// Setup Server
app.listen(5000);
html for login
<h1>Login</h1>
<form action="register" method="post">
<div>
<label for="name">username</label>
<input type="text" id="name" name="name" required>
</div>
<br>
<div>
<label for="name">password</label>
<input type="text" id="password" password="password"required>
</div>
<br>
<button type="submit">Login</button>
<br>
Register
</form>
<br>
back to Homepage
html for register
<h1>register</h1>
<form action="register" method="POST">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
</div>
<br>
<div>
<label for="email">email</label>
<input type="email" id="email" name="email" required>
</div>
<br>
<div>
<label for="password">password</label>
<input type="password" id="password" password="password"required>
</div>
<br>
<button type="submit">Register</button>
<br>
Login
</form>
<br>
back to Homepage
The request body needs to be parsed. Add this above your routes:
app.use(express.json());
^^^ Scratch this part. It's only needed with a JSON payload ^^^
In your html you have password="password" instead of name="password" for the password input element.
Why is the form data not being stored in req.body?
EJS/HTML
<form onsubmit="EditJob()" class="editForm">
<div class="form-group-edit">
<label for="position">Position</label>
<input type="position" id="position" name="position" class="form-control" placeholder="Enter Position Title"
/>
</div>
<div class="form-group-edit">
<label for="company">Company</label>
<input type="company" id="company" name="company" class="form-control" placeholder="Enter Company Name"
/>
</div>
<button type="submit" class="edit">
<i class="fas fa-plus"></i>
</button>
</form>
Client JS
const EditJob = () => {
const id = ####;
const url = `http://localhost:5000/dashboard/${id}`;
axios.put(url).then(res => {
console.log(res);
});
};
Server JS
router.put("/:id", (req, res) => {
Job.findByIdAndUpdate(req.params.id, {
position: req.body.position,
company: req.body.company,
status: req.body.status
})
...
...
});
Updated doc in my database results in {position: null, company: null, status: null}..
Make sure you're using body-parser, or set your express middleware like code below:
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
⚠️ When you're using axios.put(), make sure you passing your data in there. You can read the documentation here
An Example: Axios Put
axios.put(endPoint, data, config).then(...).catch(...)
I hope it's can help you.
I want to send/add notification data in database that contains image with some text data so I am not able to add this data in firebase. I tried some code for only data insertion, but it doesn't work and How do I add image in firebase?
I am adding database which is made manually for notification. I want to add further more notifications with image
database
This is my html form
<form method=post enctype="multipart/form-data">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label>Title</label>
<input type="text" id="title" class="form-control" placeholder="Company" >
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Image</label>
<input type="image" class="form-control" placeholder="Image">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputEmail1">Redeem Steps</label>
<input type="text" id="redeem" class="form-control" placeholder="Redeem Steps">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Description</label>
<textarea rows="5" id="description" class="form-control" placeholder="Here can be your description"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" >
Image 1 <span style="color:red">*</span><!--<input type="file" id="image" name="img1" required>-->
</div>
</div>
<button type="submit" id="submitBtn" class="btn btn-info btn-fill pull-right" onclick="submitclick()">Send notification</button>
<div class="clearfix"></div>
</form>
this is js file
var title=document.getElementById("title");
var redeem=document.getElementById("redeem");
var description=document.getElementById("description");
var image=document.getElementById("image");
var submitBtn=document.getElementById("submitBtn");
var Id=1;
function submitclick(){
var firebaseref=firebase.database().ref();
var messagetitle=title.value;
var messageredeem=redeem.value;
var messagedescription=description.value;
//var messageimage=image.value;
console.log(messagetitle);
console.log(messageredeem);
console.log(messagedescription);
//console.log(messageimage);
//firebaseref.child("notification").set("vinit");
//firebaseref.child("notification").set("2");
//firebaseref.child("notification").set("messagedescription");
//firebaseref.child("notification").set("messageimage");
firebase.database().ref('notification/'+Id).set({
title : messagetitle,
redeem : messageredeem,
description : messagedescription
image : messageimage
});
console.log(Id);
Id++;
console.log(Id);
}
You cannot upload image directly into the firebase database. You have to upload the image into the firebase storage first, then you can store the image name/location/downloadUrl in the database if you want. Altough, store the download url is not the best practice.
const file = ...
const metadata = { contentType: 'image/jpeg' }; // or whatever you want
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child(`images/${file.name}`).put(file, metadata);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {
// If you want to show upload progress, do whatever you want with progress...
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING:
console.log('Upload is running');
break;
}
}, error => {
console.log(error);
}, () => {
// upload finished with success, you can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
console.log(downloadURL);
});
});
If you want to store the downloadUrl into the databse then you have to store tha downloadUrl into a variable or put the database set into the upload finished callback.
The database set part should work with this way:
// The id should foloow your database structure,
// based on your posted image, should look like this:
// `noti_${id}` where the id is a number.
firebase.database().ref(`notification/${id}`).set({
...uploadData,
image: downloadUrl
});
Also, I hardly recommend you to use async await to handle promises and use cloud firestore instead of realtime database.
When I post form data to routing then, getting a undefined parameter error. I can't to send the form parameter to routing file. Please help me. Here is my code with files name
Getting Error
TypeError: Cannot read property 'username' of undefined
node.js
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
app.route('/').get(function(req,res) {
fs.readFile('./html/registers.html',function(err,data) {
res.writeHead(200,{'Content_type':'text/html'});
res.write(data);
res.end();
});
});
app.post('/formData', function(req, res) {
var username = req.body.username;
var password = req.body.password;
console.log("post received: %s %s", username, password);
});
register.js
<form action="formData" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" placeholder="Enter username" name="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="password">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Please replace the following
<form action="formData" enctype="multipart/form-data" method="post">
By
<form action="/formData" method="post">
Before the route function add following
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));