I currently have an app.js file and an index.html file, I want to pass data from a index.html to app.js.
I am trying to use expressJS to perform a post request but is doesn't seem to be handling the data.
HTML:
<form action="./index.html" method="post">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
NodeJS:
var express = require("express");
var app = express();
app.post('/', urlencodedParser, function(req,res){
console.log(req.body);
});
On the server command line I am getting /POST so I is registering that a post request is being made but console.log() isn't initialising with the data.
I managed to make a working example and have uploaded it to this repo.
https://github.com/crimson-eagle/nodeJS-POST-FORM
Related
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".
My NodeJS server uploads files to amazon using a secret form. With that said, I want to add extra security by providing a password field to that form - problem is, when I do that, my server does not get that property when I try to access it through req.body.pass
My code:
//Express NodeJS Server:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/upload', function(req, res, next) {
console.log(req.body.pass); //undefined, but why? when I remove enctype='multipart/form-data' it works
})
//HTML
<form action="/upload" method="post" enctype='multipart/form-data'>
<input type="file" name="name" value="">
<input type="file" name="email" value="">
<input type="file" name="age" value="">
<br>Password: <input type = "password" name = "pass"><br>
<br><input type="submit" value="Submit">
</form>
When I remove the following:
enctype='multipart/form-data'
the field pass works.. what am I doing wrong here?
As the bodyParser middleware names suggest, they only handle 'application/json' and 'application/x-www-form-urlencoded' forms. You will need a separate module to handle multipart/form-data forms, such as multer.
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');
});
When I set up my form without specifying an enctype, Firefox automatically sets it to application/x-www-form-urlencoded and req.body contains a nice, JSON representation of all the parameters entered into the form. But when I change the enctype to multipart/form-data req.body is suddenly empty.
This is my form:
<form action="/create" method="post" enctype="multipart/form-data">
<fieldset>
<div>
<label>Category:</label>
</div>
<div>
<select name="category">
<option value="standard">Standard</option>
<option value="custom">Custom</option>
</div>
<div>
<input type="text" name="description">
</div>
<div>
<label>User ID:</label>
</div>
<div>
<input type="text" name="userid">
</div>
<div>
<input type="submit" value="Go">
</div>
</fieldset>
</form>
Doing a console.log(JSON.stringify(req.body, null, 2)); prints out an empty object when enctype is multipart/form-data and when enctype is not specified, it prints out something like:
{
category: "standard",
userid: "foo"
}
Any reason this is happening?
Try use busboy-body-parser to retrieve the request body parameters and the files.
start.js
var bodyParser = require('body-parser');
var busboyBodyParser = require('busboy-body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}));
// parse application/json
app.use(bodyParser.json());
//parse multipart/form-data
app.use(busboyBodyParser());
controllers/someController.js
someAction: function(req,res){
if(req.method == "POST"){
res.end(JSON.stringify(req.body)+JSON.stringify(req.files));
}
}
//{"text":"testx"}{"anexo":{"data":{"type":"Buffer","data":.... }}}
//req.body = {"text":"testx"}
//req.files = {"anexo":{"data":{"type":"Buffer","data":.... }}}
views/someController/someAction.html
<form method="post" id="multipart" enctype="multipart/form-data">
<input type="text" id="text1" name="text" value="testx" />
<input type="file" id="anexo" name="anexo" />
<input type="submit" value="Enviar" />
</form>
To create a file uploaded, you need work if the stream, for example:
/* file props
{
"data":{"type":"Buffer","data":.... },
"fieldname":"anexo",
"originalname":"images (1).jpg",
"encoding":"7bit",
"mimetype":"image/jpeg",
"destination":"c:\\live\\sources\\uploads\\",
"filename":"eventclock_images (1)_1443706175833.jpg",
"path":"c:\\live\\sources\\uploads\\eventclock_images(1)_1443706175833.jpg",
"size":9986
}
*/
var fileStream = fs.createWriteStream(file.path);
fileStream.write(file.data);
fileStream.end();
fileStream.on('error', function (err) {
//console.log("error",err);
});
fileStream.on('finish', function (res) {
//console.log("finish",res);
});
Sounds like you're using express.urlencoded() instead of express.multipart().
I think #robertklep is correct, but I disagree with his answer. express.multipart() is deprecated and should not be used.
If you need multipart form processing, I highly recommend Busboy. If you want all the details, see this answer.
npm install multer --save
in main.js
var multer = require('multer');
var upload = multer()
router.route("/quotes").post(upload.array(),function(req, res, next){
name = req.body.name;
email = req.body.email;
}