POST data using node.js - javascript

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.

Related

Send new HTML page and make GET request to it after POST request from original page

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>

Socket.emit not going through

index.js
var app = require('express')();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
server.listen(process.env.PORT || 3000);
app.use(require('express').static(path.join(__dirname)));
console.log('server running');
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
var addedUser = false;
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', data);
});
});
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
When I start up the server, the console logs "server running" fine. I can't get the submit post button to do anything. None of the debug console messages appear and nothing happens. It's supposed to emit "new post" when the submit button is clicked but it looks as if nothing goes through
I was able to get your code to work on my own computer like this:
index.js
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.use(express.static(__dirname));
console.log('server running');
io.on('connection', function (socket) {
console.log("connection");
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', post);
});
});
server.listen(process.env.PORT || 3000);
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="/client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
Changes to index.js
Define express variable so it can be reused.
Define app.get() before app.use(express.static(...)) so we're sure to serve index.html with the app.get() and not from the static location.
Change res.sendfile() to res.sendFile()`
Change socket.emit("posted", data) to socket.emit("posted", post).
Move server.listen() to end after everything else is set up.
Remove path.join() from express.static() call since it is not needed there.
Add path.join() to res.sendFile() call for cross platform safety in path building.
Of these, the only one I'm sure was causing an error was #4, the others are good housekeeping.
Changes to client.js
None
Changes to index.html
Change path to client.js to /client.js.
If this code doesn't work on heroku, then you either don't have files positioned in the right directories or heroku is not configured properly to allow your app or socket.io to work properly. If I were you, I would first verify that this code work on your own local computer and only then, go try it on heroku to eliminate variables first.

how can I make the client talk to the express server?

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

Cannot post in node.js

I want to upload file using node.js , being new to it a tried to check if the file is being send to server.
html
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="img" method="POST"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
js
var express = require("express");
var app=express();
var http=require("http").Server(app);
app.get("/",function(req,res){
res.end("hello")
});
app.get("/upload",function(req,res){
res.sendFile(__dirname + "/form.html")
})
app.post("/img",function(req,res){
if(req.files){
console.log(req.files.file.name);
}
else{
console.log("ee")
}
});
http.listen(3000,function(){
console.log("listening on 3000")
})
When i upload something , it throws error
Cannot read files of undefined
Being new to back end i have no idea why its happening , why doesnt the server recieve the file?
You need to app.use() a fileparser. For example, you could use connect-busboy. You can get more information about options and usage at above link; a simple setup would be somehting like this:
var busboy = require('connect-busboy');
app.use(busboy());
app.post("/img",function(req,res){
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
// ...
});
req.busboy.on('field', function (key, value, keyTruncated, valueTruncated) {
// ...
});
req.pipe(req.busboy);
// etc ...
});
As stated in the above answer, you must use a body parser for multipart bodies, but the better solution is to use the express middleware multer which lets you to use req.files just like in your OP.
Also, multer is built on top of busboy which is the fastest multipart body parser for node.js
With multer:
var express = require('express'),
multer = require("multer"),
app = express();
app.use(multer({
dest: path.resolve(__root + path.sep + config.get("localFolders").rawImages),
limits: {
files: 2
}
}));
// handle file upload
app.post("/img", function (req, res, next) {
var image = req.files.image;
// do something with image;
console.log(image.name);
});
Have a look on the documentation for multer within the link provided above. Good luck. :)

NodeJS res.sendFile not sending images or directorys

so as said above, i run the html file only and i'm able to see the pictures, but when i run the file via node it sends me a 404 error on the file i used.
<html>
<body>
<img src="aaa.jpg" />
<script src="/socket.io/socket.io.js">
</script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
</script>
</body>
</html>
and the node code
var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});
how can i stop this from happening?
To serve static files such as images and scripts, you need to include a middleware that serves static files. Put all your static files inside of a public directory and serve them like this.
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
// Serve static files
app.use(express.static(__dirname + '/public'));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});

Categories