I have a simple NodeJs app, and trying to build a simple authentification form. But for some reason, i'm not able to get the entred data in the form. Here's my code :
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser= require ('body-parser');
var user = require('./routes/user');
var login = require('./routes/login');
var jwt = require('jsonwebtoken');
var app = express();
app.use(bodyParser.json());
app.use(cookieParser());
app.get('/userprofile', user.getUserInfos);
app.post('/users', user.createUser);
app.get('/login', function (req, res) {
var html='';
html +="<body>";
html += "<form action='/login' method='post' name='logingorm' enctype=\"application/json\">";
html += "Username:<input type= 'text' name='username'><br>";
html += "Password:<input type='password' name='password'><br>";
html += "<input type='submit' value='submit'>";
html += "</form>";
html += "</body>";
res.send(html);
});
app.post('/login', user.login);
app.listen(3000);
console.log('Listening on port 3000...');
And then, the login function called when a post is received on /login :
exports.login= function(req, res) {
console.log(req.body);
}
Always get {} as result of my console.log
Any idea ?
Thanks a lot
application/json is not a valid form encoding. When the browser sees that, it falls back to application/x-www-form-urlencoded.
bodyParser.json() ignores requests with MIME types other than application/json, and even if it didn't, it wouldn't be able to parse the urlencoded data. Use bodyParser.urlencoded() instead.
app.use(bodyParser.urlencoded({extended: false}));
I think that might be because there is no 'value' attribute written for both the input tags. Try writing them and check.
Related
I'm new to Node.js and JavaScript. I have a specific problem but mostly need advice on the best solution.
I'm running a Node server. I want the client to be able to submit a string to the server, then the server to display a new HTML page that shows the string data.
I'm using Express and Socket.io.
In the following files, the client sees index.html, then after submitting the form it sees return.html. I print the input string to the console, and the output is as expected (whatever the user enters). But the return.html is never updated with the input string.
I also tried sending the return.html page and the change_result call in an async series, but the sendFile function never ends and the second function in the series is never called. In previous attempts it worked intermittently with a setTimeout around the emit('change_result') function.
Why doesn't the call to change_result do anything? I used the same technique to update the headings of the original index.html in previous versions. Should I be routing to localhost.../return.html and sending the post data there, or something like that?
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser') //for POST request
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
server.listen(8080, function() {
console.log("Server running on port 8080.");
});
var dir = __dirname;
app.get('/', function(req, res) {
res.sendFile(dir + '/index.html');
});
app.post('/', function(req, res) {
var query1=req.body.input1
console.log("Server: In post request.")
console.log(query1);
res.sendFile(dir + '/return.html');
io.emit('change_result', {
result: query1
});
});
index.html
<!DOCTYPE html>
<html>
<body id="body">
<form method="post" action="http://localhost:8080">
String: <input type="text" name="input1" id="input1" />
<input type="submit" id="button1" value="Submit" />
</form>
</body>
</html>
return.html
<!DOCTYPE html>
<html>
<body id="body">
<p id="heading1">Result: </p>
<script>
document.addEventListener('DOMContentLoaded', function() {
var socket = io();
socket.on('change_result', function(data) {
document.getElementById('heading1').innerHTML = "Result: \""+data.result"\"";
});
});
</script>
</body>
</html>
I'm not knee-deep inside socket.io, but IMO the problem is, that the server has no way to know if any listeners are ready.
I think you should emit a 'ready' event, once the return.html is loaded, then listen to 'change_result'. Also separate the socket communication from the POST response on the server. Like so.
server.js
var query;
app.get('/', function(req, res) {
res.sendFile(dir + '/index.html');
});
app.post('/', function(req, res) {
query = req.body.input1;
console.log("Server: In post request.");
console.log(query);
res.sendFile(dir + '/return.html');
});
io.on('connection', function(socket) {
socket.on('ready', function() {
socket.emit('change_result', {result: query});
});
});
return.html
<script>
document.addEventListener('DOMContentLoaded', function() {
var socket = io();
socket.emit('ready', function(data) {});
socket.on('change_result', function(data) {
document.getElementById('heading1').innerHTML = "Result: \""+data.result + "\"";
});
});
</script>
So I am trying to link this interface to a server so that the message I input in the front end is Posted in a separate webpage hosted on the server. eg "Hello [name]"
This is the interface:
<form id="loginformA" action="userlogin" method="post">
<div>
<label for="Insert message here">Message: </label>
<input type="text" id="message" name="message"></input>
</div>
and this is the server I am trying to post the message to:
var express = require('express');
var app = express();
app.use(express.static('public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/userlogin", function(request, response) {
response.send( "Hello " + request.body.message );
});
app.listen(process.env.PORT || 8080, process.env.IP);
I am just not sure how to make the interface and server talk to each other. I would also like to store all the messages in a db too, but that is for later after I figure this out.
Thanks!
Right now your form submits to /userlogin. You should define that route in your server like this:
app.post('/userlogin', function(req, res){
res.send('Hello' + req.body.message);
}
req.body is basically the post data submitted by your form, in this case only the input named 'message.'
any time you wish to submit a form to a node server, ensure the action corresponds to a route or method with an identical name.
From your html ...
app.post('/userlogin', function(request, response) {
response.send( "Welcome, your message is: " + request.body.message );
});
If you look at code below on the client.on method, I res.write the entire output file because I did not know how to get the message to display with the html file. Is there a similar way of doing this rather than res.writing anything? Res.write is also very slow while when I used res.send it was very fast. Is there any other way I can do this? I am fairly new to node js
//Sending UDP message to TFTP server
//dgram modeule to create UDP socket
var express= require('express'), fs= require('fs'),path = require('path'),util = require('util'),dgram= require('dgram'),client= dgram.createSocket('udp4'),bodyParser = require('body-parser'),app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(express.static('public'));
//Reading in the html file for input page
app.get('/', function(req, res){
var html = fs.readFileSync('index2.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//reading in html file for output page
app.get('/output', function(req, res){
var html = fs.readFileSync('index3.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//Recieving UDP message
app.post('/output', function(req, res){
//Define the host and port values of UDP
var HOST= '192.168.0.136';
var PORT= 69;
//Reading in the user's command, converting to hex
var message = new Buffer(req.body.number, 'hex');
//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) throw err;
});
//Recieving message back and printing it out to webpage
client.on('message', function (message) {
res.write('<html>');
res.write('<head>');
res.write('<meta name="viewport" content="width=device-width">');
res.write('<link rel="stylesheet" type="text/css" href="style.css" media="screen" />');
res.write('</head>');
res.write('</body>');
res.write('<img src="logo.png" alt="rolls royce logo">');
res.write('<ul>');
res.write('<li>Input</li>');
res.write('<li><a class="active" href="/output">Output</a></li>');
res.write(' </ul>');
res.write('</br></br>')
res.write('<div>');
res.write(' <h4>Output is:</h4>');
res.write(message.toString());
res.write('</div>');
res.write('</body>');
res.write('</html>');
});
});
//Setting up listening server
app.listen(3000, "192.168.0.136");
console.log('Listening at 192.168.0.136:3000');
You could write an HTML template, save it into a part of the file system which is accessible from the server, then return it to the HTTP client feeded with the right value.
You could write your own template engine (and use regular expressions to make the correct substitutions), or you could you use Jade for instance.
client.on('message', function(message) {
fs.readFile('/etc/templates/message.jade', function(_, template) {
let body = jade.compile(template)({
message: message.toString()
});
return res.end(body);
});
});
Where message.jade might be
doctype html
html
body
h4 Output is: #{message}
i am trying to insert some data to database using node and mysql i manage to get it done, but after query response the browser loads continuously i tried pooling still nothing happens
Here is my code
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var sql = require('mysql');
var pool = sql.createPool({
host : 'localhost',
user : 'root',
password : '',
port : '3306',
database : 'node'
});
app.get('/nodeThis', function (req, res) {
res.sendFile(__dirname + '/insert.html');
});
app.post('/nodeThis', urlencodedParser, function (req, res) {
var post={user_name:req.body.name1,user_what:req.body.what,user_why:req.body.why};
pool.getConnection(function(err, connection){
connection.query('INSERT INTO user SET ?', post, function(err){
if(err){
console.log(err);
}else{
console.log('succes');
}
});
connection.release();
});
});
server.listen(3000);
Here is how i pass the data from HTML to node
<html>
<body>
<div>
<form action="/nodeThis" method="post">
<input type="text" name="name1">
<input type="text" name="what">
<input type="text" name="why">
<button class="boom">Submit</button>
</form>
</div>
</body>
</html>
After the database operation, you aren't sending any response to the browser; you just sent an output to the console instead; the browser was waiting for a response that never came
If you insert res.sendFile(__dirname + '/insert.html'); or some other response after the console.log('succes');, you'll see an output on the browser.
That being said, I hope this is just a proof of concept and not a production code.
Update Based on the Comment
Retrieving the number of rows affected
After running the executing the database insertion function
db.query("insert into table", [data-to-insert], function(err, result){
//to retrieve the number of rows affected
var number_of_rows = result.affectedRows
})
the result has a property called affectedRows that allows the user to know how many rows were inserted, updated, or deleted.
To retrieve the primary id of the inserted row (if it has one), result has a property called insertId.
var id = result.insertId
Hope this helps!
I'm trying to get form data to node server using POST method.
This is my HTML code,
<html>
<head>
<title>
Node Architecture
</title>
</head>
<body>
<h1>Node Architecture</h1>
<h3>Enter Your name.</h3>
<form action="/" method="POST">
<input type="text" name="eventname" />
<input type="submit" value="Go" />
</form>
</body>
</html>
This is my node app, index.js
var app = require('express')();
var http = require('http').Server(app);
//var io = require('socket.io')(http);
//var qs = require('querystring');
app.get('/', function(req, res){
res.sendfile('index.html');
});
app.get('/events', function(req, res){
res.sendfile('events.html');
});
app.get('/movie', function(req, res){
res.sendfile('movie.html');
});
app.post('/', function(req, res) {
var name = req.body.eventname;
console.log(name);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now when I click submit I get an error message which is as follows,
TypeError: Cannot read property 'eventname' of undefined at Object.handle
How do I print the entered name to my console?
Express doesn't parse request body by default, you will have to use a middleware to do that.
Try this.
var express = require('express');
var app = express()
.use(express.bodyParser());
...
...
Also, you should read this article. It explains some of the problems (and their solutions) related to common body parsing approach.
Add these lines into your app.js.
require body-parser.
var bodyParser = require('body-parser');
put before your first app.get that will be better.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
good luck.