Going nuts trying to get past this. Should be trivial, but I'm obviously doing something stupid. Goal is to upload a file inside Express. In short request.files is coming back as undefined in my route handler :
//modules ==========================================
// ExpressJS 4.0 used for the middleware and web framework
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var jsxml = require("node-jsxml");
var XMLWriter = require('xml-writer');
var request = require("request");
var fs = require('fs');
var app = express();
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
// Did I screw this up??!
app.use(bodyParser({keepExtensions:true,uploadDir: __dirname + '/public/uploads'}));
app.engine('html', require('ejs').renderFile);
app.use(cookieParser('Ronaldinho'));
app.use(session());
app.use(flash());
My file system:
Here's the form where a file is submitted (via a plugin called DropZone):
<div id="dropzone">
<form action="/uploads" name="upload" class="dropzone" id="demo-upload" enctype="multipart/form-data" method="post">
<input type="file" name="theFile" />
</form>
</div>
and the handler for the route:
app.post('/uploads', function (request, response) {
console.log('arrived');
console.log('1st TEST: ' + (request.files));
console.log('2nd TEST: ' + request.files.theFile.name);
fs.readFile(request.files.theFile.path, function (err, data) {
var newPath = "/home/path/to/your/directory/"+request.files.theFile.name;
console.log (newPath);
fs.writeFile(newPath, data, function (err) {
res.send("hi");
});
});
});
I hit the function above every time I upload a file, but find that request.files is undefined. Here's the result on the console (I'm using Brackets - interesting to me that I never even see the second test hit the console window...):
Any ideas what I'm screwing up?
Related
I'm working on a node.js project that involves selecting someones' name and redirecting the user for more information. However, when I try to console.log the result, just to check that I can retrieve the values, I get nothing.
Below is an example of my code:
function displayDetailed(data, req) {
names = data[0];
var input = '<select name = "dropDown" onChange = "testing(this)">;
for (var i = 0; i < names.length; i++) {
input += '<option value= "' + i + '" name = "employee" > ' + names[i] + ' </option>';
}
input += '</select><br>';
var myData = {
test: req.body
}
console.log(myData);
return '<!DOCTYPE html><head></head><body>' + input + '</body></html>';
}
function testing(name) {
console.log('Testing! ' + name);
}
Clearly, I just want the employee's name to be printed off onto the console for the moment. However, nothing is popping up on the console, be it the name or any errors.
I've also tried multiple solutions I've seen on other StackOverflow posts ( Example, Example1 ). That's where I got the idea for the test var. For some reason, the request's body does not exist when I try to call it and just returns undefined.
I also can't call document.getElementById since node.js doesn't have a DOM. The solutions linked implement this function, which I cannot call because node.js doesn't allow me to call the html document that the user is working on.
This function will be returning an HTML string to a res.send call within an express app.get.
Short answer:
I suspect your problem is you're not using a body parser middleware to parse the request body.
Longer version:
Suppose you have an HTML file named index.html in a directory named html in the root of your project:
<!doctype html>
<meta charset=utf-8>
<title>Test</title>
<body>
<form action="/" method="post">
<select name="values">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
</select>
<input type="submit">
</form>
</body>
You can use the built-in static middleware to serve that file to clients (or build the HTML string and send it as a response to clients or maybe use a template engine and make your life easier) and then use a body parser middleware (like this one) to parse the request body when the form is submitted:
const http = require('http');
const path = require('path');
const bodyparser = require('body-parser'); // npm i body-parser
const express = require('express');
const app = express();
const PORT = process.env.PORT || 8080;
const server = http.createServer(app);
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
app.use(express.static(path.join(__dirname, './html')));
app.use(bodyparser.urlencoded({extended: true}));
app.post('/', (req, res) => {
res.setHeader('content-type', 'text/plain');
res.end(`You have selected: ${req.body.values}`);
});
Scenario:
I have a server which is accessed by multiple users. Server for ex: http://127.0.0.1:8081
It has one button and by clicking on it, it runs one selenium automated test.
I want to get a list of tests currently running by multiple users.
So for ex: if 5 users are accessing that server and clicked on that button 2 times it means that automated tests running are 10.
How can I get above count in node.js express like how many processes are running?
My server.js :
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send(
'<form action="/server" method="POST">' +
' <input type="submit" name="server" value="Run Script" />' +
'</form>');
});
app.post('/server', function (req, res) {
var fork = require('child_process').fork;
var child = fork('./test');
res.send('Test Started....');
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
Not tested, but the following should do something like what your after.
Not sure were you wanted to access counter, so done another route /counter that echo the current counter out.
var express = require('express');
var app = express();
var counter = 0;
app.get('/', function (req, res) {
res.send(
'<form action="/server" method="POST">' +
' <input type="submit" name="server" value="Run Script" />' +
'</form>');
});
app.get('/counter', function (req, res) {
res.end("Counter = " + counter);
});
app.post('/server', function (req, res) {
var fork = require('child_process').fork;
var child = fork('./test');
counter ++;
child.on("close", function () { counter --; });
res.send('Test Started....');
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
You can maintain global count for clicked button.
global.total_tests = 0; // note this line
var express = require('express');
var app = express();
app.post('/server', function (req, res) {
var fork = require('child_process').fork;
var child = fork('./test');
res.send('Test Started....');
total_tests++; // note this line
});
I hope this help.
Thanks.
I'd recommend using ps-node as suggested in this earlier Stackoverflow post.
I am trying to learn Node and build a simple chat application. It seems like everyone uses socket.io. I would like to understand how to do this on a more fundamental level using get and post.
Basically, all I want to do is have a form that takes an input and reposts it below the form for everyone to see.
This is what I have so far:
//Requirements
var express = require('express');
var app = express();
//GET
app.get('/', function (req, res) {
// res.send('Hello World!');
var response =
"<HEAD>"+
"<title>Chat</title>\n"+
"</HEAD>\n"+
"<BODY>\n"+
"<FORM action=\"/\" method=\"get\">\n" +
"<P>\n" +
"Enter a phrase: <INPUT type=\"text\" name=\"phrase\"><BR>\n" +
"<INPUT type=\"submit\" value=\"Send\">\n" +
"</P>\n" +
"</FORM>\n" +
"<P>phrase</P>\n"+
"</BODY>";
var phrase = req.query.phrase;
if(!phrase){
res.send(response);
}else{
res.send(response);
res.send(phrase);
}
});
//For testing
app.get('/test', function(req, res){
res.send('I am a robot');
console.log('told visiter I am a robot');
});
//Run the app
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
I've been trying a bunch of things, but I am pretty stumped.
Did you hear about messaging backend jxm.io?
It works with JXcore (open sourced fork of Node.JS). JXM itself is an open source project, which you can find on github: jxm.
It's really fast and efficient, you can check some tutorials. For example, below is minimal code, that you need to run on server-side:
var server = require('jxm');
server.setApplication("Hello World", "/helloworld", "STANDARD-KEY-CHANGE-THIS");
server.addJSMethod("serverMethod", function (env, params) {
server.sendCallBack(env, params + " World!");
});
server.start();
The client's part can be found here:
Browser Client (JavaScript)
JXM also supports Java clients (runs on android) and node clients.
I'm trying to communicate node.js and a HTML script with socket.io. I'm trying that when i choose some value with a radio button, socket.io sends this value to node.js and then, return to the console. My problem is that socket.io doesn't send anything. I know it doesn't enter the socket function because i write an alarm in html if it enters, and nothing.
Node.js code is this:
var express = require("express");
var http = require("http");
var socketIO = require("socket.io");
var app = express();
app.get("/", function(req, res){
res.sendfile("./toggle?.html");
});
var server = http.createServer(app);
var io = socketIO.listen(server, {log: false});
io.sockets.on("connection", function(socket){
socket.on("sendVar", function(value){
console.log(value)
});
});
server.listen(5000);
And the HTML script is this:
<html>
<input type="radio" name="group1" value=1> ON<br>
<input type="radio" name="group1" value=0 checked> OFF<br>
<INPUT TYPE="Button" VALUE="Proceed" onClick="showBoxes(this.form)">
<script>
var radios = document.getElementsByName('group1');
function showBoxes(frm){
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
var x=radios[i].value;
alert(radios[i].value)
//Send the value of the radio button
var socket = io.connect("http://localhost:5000"); //client connection
socket.on("connect", function(){
alert("connected!")
socket.emit("sendVar", x);
});
break;
}
}
}
</script>
</html>
Do you have a specific need to have this web socket open? currently what you have an AJAX call would be more suited. you can handle this with the normal request, response method using express.
You can use a simple express get handler:
app.get('/', function(req, res){
res.send('hello world');
});
or you can use the router:
var app = express();
app.route('/events')
.all(function(req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
})
.get(function(req, res, next) {
res.json(...);
})
.post(function(req, res, next) {
// maybe add a new event...
})
each solution would be more suited that a socket.
source: http://expressjs.com/api.html
Here I have a code for sum 3 numbers i+j+k but I waht to know how to configure server file to work with setTimeout function... is there some restriction?
so, here is mycode:
index.jade
!!! 5
html
head
title Test
body
form(name='form1', method='post', action='')
label(for='1')
input#1(type='text', name='1')
label(for='2')
input#2(type='text', name='2')
label(for='3')
input#3(type='text', name='3')
input(name='submit', type='button', value='submit')
span #{result}
app.js
var express = require('express');
app = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", { layout: false });
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.use(express.bodyParser());
app.get('/', function(req, res){
var result;
res.render('index', {result: ''});
});
app.post('/', function(req, res){
var i = req.param('1', 0);
i = parseInt(i);
var j = req.param('2', 0);
j = parseInt(j);
var k = req.param('3', 0);
k = parseInt(k);
var r = i+j+k;
res.render('index', {result:r});
});
app.listen(3010);
How etc. to block user action (click,doubleclick,rightclick) and show him a div with text "You can do any action" in first 5 seconds and after that user can do action but after 60 seconds again can't do any action... Can I do this with setTimout function or HOW???
sorry for my english
You cannot do this on the server side. You have to insert a client side javascript that blocks the interaction and unblocks it again after 5 sec.
The code for doing this on the client side would be something like this:
// this code should be executed when the client receives a message from the server.
var overlay = document.getElementById("your-element-id");
overlay.style.visibility = "visible";
window.setTimeout(function () {
overlay.style.visibility = "hidden";
}, 5000);
You should take the following steps to achieve what you want:
1. The user loads the page.
2. The user receives a message from the server, stating that he is being synchronized
3. Then either after a specified time or after another message from the server you unblock the user
4. Finally you start the game