Node, Express, vanilla JS POST form not sending data to API - javascript

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

Related

Form with recaptcha redirect after submission

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>

How can I get a alert saying "Welcome" +username that I entered

So,here's my index.html file which consists of username and password input fields.So,when the user clicks on the submit button I want to get a alert saying "Welcome"+username.Im using nodejs also here. please help me.
index.html
<body>
<main class="form-signin">
<form method="post" action="/">
<h1 class="h3 mb-3 fw-normal">Login</h1>
<br/>
<div class="form-floating ">
<input type="name" class="form-control" name="username" placeholder="Enter Username...">
<label for="floatingInput">Username</label>
</div>
<div class="form-floating">
<input type="password" class="form-control" name="password" placeholder="Enter password">
<label for="floatingPassword">Password</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
</form>
</main>
</body>
Here's my server.js file where all the routes has been handled.
So below here when i click the submit button im getting the value of username entered in post request But how exactly should I create an alert?
server.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.get('/', function(req, res) {
res.sendFile(__dirname+"/index.html");
});
app.post('/', function(req,res) {
var username=req.body.username;
// I don't know what to do here exactly
});
app.listen(3000,() => {
console.log("Server started on port 3000");
});

Simple Tutorial code not getting data from a Login form (express js)

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.

How to submit form data to express server?

I have set up a basic express server to accept some information submitted through a form. Unfortunately, I have run into some problems.
I cannot log the data I receive onto the console. Can someone please help me figure this out?
app.js:
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
app.use(express.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'public')));
app.use('/',(req,res,next) => {
res.sendFile(path.join(__dirname,'public','index.html'));
});
app.post('/api', (req, res) => {
console.log(req);
})
app.listen(port, () => console.log(`App is listening on port ${port}!`))
And here's the form itself:
index.html:
<body>
<h1>Hello there!</h1>
<form id='form' method="POST" action="/api">
<input id='textField' type='text' name='name' placeholder='Enter your name'>
<p>Enter your date of birth:</p>
<div class='dob'>
<input id='date' type='number' name='date' placeholder='Date'>
<select id='dobMonth' name="month">
<option value="default">Month</option>
<option value="Jan">January</option>
<option value="Feb">February</option>
<option value="Mar">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="Aug">August</option>
<option value="Sept">Septmeber</option>
<option value="Oct">October</option>
<option value="Nov">November</option>
<option value="Dec">December</option>
</select>
<input id='year' type='number' name='year' placeholder='Year'>
</div>
<input id='btn' type='submit'>
</form>
<script src='script.js'></script>
</body>
Thanks in advance :)
The problem is just the order of your routes. The first path you specify:
app.use('/',(req,res,next) => {
res.sendFile(path.join(__dirname,'public','index.html'));
});
Is acting as a catch-all, since every path on the server includes '/'
If you switch the order and make the catch-all last, this should work just fine for you.
app.get('/api', (req, res) => {
console.log(req);
})
app.use('/',(req,res,next) => {
res.sendFile(path.join(__dirname,'public','index.html'));
});
I think for this you need body-parser middleware and tnen you can get parsed data from request:
here is simple example:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
// create user in req.body
})
But it's does not handle multipart bodies (post with files).
Due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
busboy
formidable
multer
<form class="innerWidth" action="/contact-detail/" method="post">
<label for="">Name</label>
<input type="text" name="name">
<label for="">Business Email</label>
<input type="email" name="email" >
<label for="">Role</label>
<input type="text" name="role">
<label for="">Contact No.</label>
<input class="contactInput" type="text" name="number" >
<label for="">Message</label>
<input class="messageInput" type="text" name="message" >
<div class="submitBtn">
<input type="submit" value="Submit">
</div>
</form>
app.post('/contact-detail/', jsonParser, function(req, res) {
// create user in req.body
})

Post form data in route in node js

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

Categories