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>
Related
I am using Node JS and Express JS to make a form submission push data to the database.
This is my form
<form action="/pokedex/register/poke_submission" method="POST">
<div>
<label for="name">Pokemon</label>
<input type="text" name="name" id="name" required />
</div>
<div>
<label for="number">Number</label>
<input type="text" name="number" id="number" required />
</div>
<div>
<label for="primaryType">Primary Type</label>
<input
type="text"
name="primaryType"
id="primaryType"
required
/>
</div>
<div>
<label for="secondayType">Secondary Type</label>
<input type="text" name="secondayType" id="secondayType" />
</div>
This is my POST API
app.post("/pokedex/register/poke_submission", async function (req, res) {
const poke = new Pokemon({
information: {
name: req.body.name,
dexNumber: req.body.dexNumber,
primaryType: req.body.primaryType,
secondaryType: req.body.secondaryType, // Not required
});
try {
const newPokemon = await poke.save();
res.send(newPokemon);
} catch (err) {
res.send(req.body);
console.log(err);
}
});
and I am using these two
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
When I hit Submit, it sends me to /pokedex/register/poke_submission but with a 405 error.
It seems it should be as below in code:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
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.
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.
i want to render data concerning the authentication status to my login form which is at index.html:
i tried to do that
response.render(__dirname + "/CERIGame/index.html", {
errors: "authentication failed"
});
but it doesn't work; need help
here is my project tree:
and here my server.js file:
app.get('/login', function(request, response) {
var username = request.query['username'];
var password = request.query['password'];
if (username == "" || password == "") {
response.render(__dirname + "/CERIGame/index.html", { errors: "authentication failed" });
}
});
i want to display the errors variable content in my index.html
<div class="body"></div>
<div class="grad"></div>
<div class="col-xs-4">
<div class="header">
<div><b>Bienvenue sur<span>qUIZZ CERI</span><b></div>
</div>
</div>
<br>
<form class="col-xs-8" method="get" action="/login">
<div class="login">
<input type="text" placeholder="username"name="username"><br>
<input type="password" placeholder="password"name="password"><br>
<input type="submit" value="Login">
</div>
</form>
I have some code that is supposed to validate a user logging into my server, however it doesn't want to post it. My get request has no problem loading the very same "/login" as my post but for some reason it doesn't want to load it during the POST. Sorry if my code is a little inefficient and hard to read, still trying to get the hang of javascript.
app.post("/login", (req, res) => {
req.body.userAgent = req.get('User-Agent');
dataServiceAuth.checkUser(req.body).then((user) => {
req.session.user = {
userName: user.username,
email: user.email,
loginHistory: user.loginHistory
}
res.redirect('/employees');
}).catch((err) => {
res.render("login", {errorMessage: err, userName: req.body.userName});
});
});
and the function in the POST
module.exports.checkUser = function (userData) {
return new Promise(function (resolve, reject) {
User.find({ user: userData.userName }).exec().then((user) => {
if (user == undefined || user.length == 0) {
reject("Unable to find user: " + userData.userName);
}
else if (user[0].password != userData.password) {
reject("Incorrect Password for user: " + userData.userName);
}
else if (user[0].password == userData.password) {
users[0].loginHistory.push({dateTime: (new Date()).toString(), userAgent: userData.userAgent});
user[0].update({userName: userData.userName}, {$set: {loginHistory: user[0].loginHistory}}.exec().then((user) => {
resolve(user[0]);
}).catch((err) => {
reject("There was an error verifying the user: ${err}");
}))
}
}).catch((err) => {
reject("Unable to find user: " + userData.user);
});
});
};
My Tree looks like this
and my Handlebars file looks like this
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Log In</h2>
<hr />
{{#if errorMessage}}
<div class="alert alertdanger">
<strong>Error:</strong> {{errorMessage}}</div>
{{/if}}
<form method="post" action="/login">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input class="form-control" id="userName" name="userName" type="text" placeholder="User Name" required value=""
/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input class="form-control" id="password" name="password" type="password" placeholder="Password" required />
</div>
</div>
</div>
<input type="submit" class="btn btn-success pull-right" value="Login" />
</form>
</div>
</div>
</div>
</body>
</html>
Express version 4 and above requires extra middle-ware layer to handle POST request. This middle-ware is called as ‘bodyParser’. This used to be internal part of Express framework but here I think you need to install it separately like this npm install --save body-parser
Firstly, You should realize that requesting the same route through GET and POST methods does different things.
When you use the GET method, the reason that it has no problem loading the page is because (from what I assume) you would have specified a specific file (probably this login form) to be rendered when a request is received.
In case of the POST request though, you are carrying out operations on the form data sent with the request, and hence there could be a number of reasons you're facing issues with it. Maybe you haven't configured bodyParser to parse nested objects, as Yaswant's answer stated. Or maybe there's some other issue in your code.
It would be helpful if you could give a little more detail on what error you're facing, and if you could post your complete app.js file.