I'm sure this is a simple thing I am missing but the internet seems devoid of the documentation to do this simple thing.
I am trying to grab data from my HTML and send it to my database. I forgot to add my script tag to the HTML for a while but it was working and sent two tests into the database before it stopped working and said my validations failed (both title and blog are required).
What am I missing? Thank you for your help!
my form:
<form
action="/api/blog"
method="POST"
id="blog-form"
class="blog-form container mt-5"
enctype="multipart/form-data">
<label for="title">Title</label>
<input type="text" name="title" />
<br />
<label for="blog">Text</label>
<textarea name="blog" rows="15" cols="120"></textarea>
<input type="submit" value="submit" />
</form>
JS:
const form = document.getElementById("blog-form");
form.onsubmit = (e) => {
e.preventDefault();
console.log(e.target.value); // this is coming back undefined
};
API route:
router.post("/blog", async (req, res) => {
console.log(req.body);
const blog = new Blog({
title: req.body.title,
blog: req.body.blog,
});
try {
await blog.save();
res.status(201).json(req.body);
} catch (err) {
console.error(err.message);
res.status(500).send("server error");
}
got it working by removing the "enctype="multipart/form-data" from the HTML and removing all of the JS
Related
I have a form that looks like:
<form method="POST">
<label>Your name:
<input name="name" required>
</label>
<input type="submit" onclick="this.form.submit(); this.disabled=true; this.value='Sending…';">
</form>
The form's backend takes upto 10 seconds to respond (blockchain!), hence the disabled input to prevent multiple retries. However it then breaks the required validation and users can send in empty payloads.
Any tips how to prevent this using Vanilla or maybe VueJS?
Many thanks,
Using Vuejs you can try :
#submit.prevent="action" in form tag instead of onClick....
add async await with try catch
if you want you can also disable your button in submit to be sure users can't send an empty payloads
here's a gist code : https://gist.github.com/jiyuuki/e6f8f7bb67b48014223d1561119ac2fa
Try to control the button with a data property like below.
export default {
name: 'Form',
data() {
return {
isLoading: false,
}
},
methods: {
async submitForm() {
this.isLoading = true;
await this.form.submit(); // Assuming this is where you make the time taking call
this.disabled=true;
this.value='Sending…';
}
}
}
<form method="POST">
<label>Your name:
<input name="name" required>
</label>
<input
:disabled="isLoading"
type="button"
#click="submitFrom">
</form>
Reset the isLoading to false after the response reaches.
I am trying to create a login page using html and node.js. I have been able to send stuff to the database using only node.js and postman but now I am trying to get it working with my html page. When trying to send stuff, I get sent back to index.html and a scripts.js error. The scripts.js error comes from the index.html page but it only happens when I get redirected. That error is not my problem though because I cant even get my db to update which is the biggest part I am trying to solve.
app.js
app.use('/public', express.static(path.join(__dirname, 'static')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'static', 'index.html'));
});
app.use(bodyParser.json());
const { urlencoded } = require('body-parser');
app.use(express.urlencoded({ extended: true }))
const authRoute = require('./routes/auth');
app.use('/api/user', authRoute);
app.use('/api/posts', postRoute);
I am using a routes folder where I contain the auth.js. auth.js also contains the methods I use to login in and registering a account
auth.js
const User = require('../models/User');
const { registerValidation, loginValidation } = require('../validation');
router.post('/register', async (req, res) => {...}
router.post('/login', async (req, res) => {...}
register.html
<form action="/" method="/api/user/register">
<input type="name" placeholder="Name" name="name" id="name" required>
<input type="text" placeholder="Email" name="email" id="email" required>
<input type="password" placeholder="Password" name="passwrd" id="password" required>
<!-- <input type="password2" placeholder="Repeat Password" name="psw-repeat" id="psw-repeat" required> -->
<!--<button type="submit" class="registerbtn">Register</button>-->
<input type="submit" value="Continue">
</form>
</div>
</div>
Using postman when I need to register a account I do
http://localhost:3000/api/user/register
{
"name": "POST MAN",
"email": "RDM#EMAIL.com",
"password": "123456"
}
Similar to login except I do /login and only use email and password. If I can get the register part working than I would be able to get the rest working as well.
Try modifying Form tag’s attributes in html
action=“BE URL or api Path”
method=“POST”
Reference: https://www.w3schools.com/tags/att_form_method.asp
I am taking my first jab at Express Node JS and thoroughly enjoying it. I'm looking to understand how to get first name and last name information input by a user to the server and displaying it in the console log.
My code in HTML is as follows:
<form action = "/getname/" method = "GET">
<p>First name: <input type="text" id="fname" name="firstname"></p>
<p>Last name: <input type="text" id="lname" name="lastname"></p>
<p><input type="button" value="Submit" id="namebutton" /></p>
<p><span id="JSONname"></span></p>
</form>
My code in Express app.js is:
app.get('/getname/', function (req, res) {
response = {
firstname: req.query.firstname,
lastname: req.query.lastname
};
console.log(response);
res.end(JSON.stringify(response));
})
I think the connection between the localhost:xxxx/getname and the server is working, however the html to getname isn't working.
Might anyone see where the code is going wrong?
The submit button must be type="submit" and not type="button".
I have created a login page using some HTML/CSS and I want the user to enter a pre-determined password, if the password is correct, they can enter the site, if not, they can't. I have looked up a lot of tutorials/sites etc. but they either use Mongodb to create unique passwords or else use Passport which is not what I'm looking for. I realise having a pre-determined password is not best practice but it suits for the scope of what I'm doing. I plan to change it once I get a basic set up going.
There is a fully functioning site when the user logs in, I just have very little experience with Node.js and not really sure how to handle the post request
This is my the form part of my HTML page (login.ejs)
<form method="post">
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
And this is my part of my server.js file
var express = require('express');
var config = require('./config');
var bodyParser = require('body-parser');
var mandrill = require('mandrill-api/mandrill');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static('dist'));
app.use(bodyParser.urlencoded({ extended: false }));
//other stuff
app.post('/login', function (req, res) {
//user enters predetermined password
//user hits the submit button
//if password = "login"
//go to home page
//if password != "login"
//go to error page
});
First, you need to specific the action attribute of the form to be the node route you want to send to. Your form will simply change to:
<form method="post" action="/login">
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
In your node file, since you are using body-parser it is very simple to access the body of the POST request.
app.post('/login', (req, res) => {
var data = req.body.name;
});
Where name is the value of the name attribute on the input tag in your form.
modify client side code as
<form method="post" action="/login">
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
and modify server side code as:
app.post('/login', function (req, res) {
if (req.body.name == "login")
res.redirect('/home');
if (req.body.name != "login")
res.redirect('/error');
});
app.get('/home', function(req, res) {
// If you are using ejs, you can render ejs
res.sendFile(__dirname + 'path_to_folder_containing_htmls/home.html');
});
app.get('/error', function(req, res) {
// If you are using ejs, you can render ejs
res.sendFile(__dirname + 'path_to_folder_containing_htmls/error.html');
});
I have a simple form, I just want to see which fields are sent to server. But in the server side, I only get the <input type="text"> field value. Why the server can't get the <select> and <input type="file" /> value?
HTML:
<form action="http://localhost:8100/" method="POST">
<div>
<select>
<option value="op1" selected="selected">Option1</option>
<option value="op2">Option2</option>
</select>
</div>
<div>
<input type="file" value="select a file"/>
</div>
<div>
<label>Your Hero: </label><input type="text" name="hero" />
</div>
<input type="submit" value="submit" />
</form>
Server:
var http = require("http");
http.createServer(function(req, res) {
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
console.log(body);
});
req.on('end', function () {
console.log("request data complete");
});
res.end("post request");
} else {
res.end("get request");
}
}).listen(8100);
Your select and file input elements are missing name attribute. All form elements you wish to be submitted must have a unique name attribute. name attribute will the identifier for the value of element when the data has been submitted through POST and GET.
You can read about it in the specs in here: http://www.w3.org/TR/html5/forms.html#naming-form-controls:-the-name-attribute
I think you just forgot the "name" attributes in this form elments. Add it and it should work. Cheers