Give value from node.js to its server's html - javascript

I need to give var into my html like server -> client
I'm not good at english and this situation is hard to explain so i will show you the code
html (index.html):
<script type="text/javascript">
console.log(tmp) //lol!
</script>
node.js:
fs.readFile('./index.html', (err, html) => {
if (err) {
response.statusCode = 404;
response.end(`error!`);
}
else
{
tmp="lol!"
response.write(html);
response.end();
}
});
server should response and give value to client same time. but it didn't work.
i don't want use external modules like express.js or ajax anything need to download things as it's possible
could you help me?

fs.readFile('./index.html', (err, html) => {
if (err) {
}
else
{
var tmp = new Object();
tmp.string = "hello world!"
var go = JSON.stringify(tmp)
res.write(`<div id="data"><div id="list" data-list='${go}'></div></div>`);
res.write(html);
res.end();
}
});
HTML:
var data = JSON.parse(document.getElementById("list").getAttribute("data-list"));
alert(data.string);
make a div element and set attribute, then write in response.

Related

Using eval in Node.js to send requests to the server using submit button and input text

So here is what I'm trying to achieve!
I want to create a very simple Node application where I can make use of the eval function by creating a input text box and a submit button. I want to be able to write things in the text box and when hitting submit to use the eval function to send this parameter to the server.
So if I write while(true) in the text box this should cause a DoS attack to the server, due to the eval vulnerability.
Here is my code so far (fix doesn't work properly)
var http = require("http");
var server = http.createServer(function(request, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write("<html>");
res.write("<head>");
res.write("<title>Hello World Page</title>");
res.write("</head>");
res.write("<body>");
res.write("Enter Some text");
res.write('<input type="text" name="fname">');
res.write('<input type="submit" value="Submit")');
var parameter = eval(req.body.fname);
res.send(parameter);
res.write("</body>");
res.write("</html>");
res.end();
});
server.listen(1337);
console.log("Server is listening");
Any ideas on how to make this work?
First - here is a good post on the topic: Accessing the HTTP message body (e.g. POST data) in node.js
A couple of minor changes to your html:
I've added a form element with an action and method set to POST. You could use GET as well to avoid some of the req.on(...) logic below.
added closing bracket for the submit button - you had a typo with a paren
When reading posted form data, you will need to read all of the data coming in until it is complete. The req parameter is an event emitter so you would use:
req.on('data', function(chunk) {...}
req.on('end', function() {...}
To buffer up the incoming data then act on it when the end of the request is reached.
The form data is encoded, so you will need to parse it using the querystring module.
I've also added just enough error checking (and fixed a few naming bugs) to get the code to function at a basic level.
Code:
var http = require("http");
var querystring = require('querystring');
var util = require('util');
var server = http.createServer(function(req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
console.log('POSTed: ' + body);
body = querystring.parse(body);
console.log('decoded: ' + util.inspect(body));
res.writeHead(200, {"Content-Type": "text/html"});
res.write("<html>");
res.write("<head>");
res.write("<title>Hello World Page</title>");
res.write("</head>");
res.write("<body>");
res.write("Enter Some text");
res.write('<form action="/" method="post">');
res.write('<input type="text" name="fname">');
res.write('<input type="submit" value="Submit">');
res.write('</form>');
if(body.fname) {
var parameter = eval(body.fname);
console.log(util.inspect(parameter));
if(parameter) {
res.write(parameter);
}
}
res.write("</body>");
res.write("</html>");
res.end();
});
});
server.listen(1337);
console.log("Server is listening");

Rendering HTML/ Cannot Get / node.js error

Ok guys, when I run my code with node.js and try to open the port on Chrome I get the error "Cannot Get /" instead of rendering the form . There are several questions on this, here but unfortunatly none helps. It would be great if you could take a look at the code and maybe state the problem.
Also here what I am trying to do : I am using import.io to take some data from trip advisor, which comes to me as JSON objects. Then I want to use a form to filter the names of the places, and give the user what he wants.
I know import.io is in beta and not a popular tool yet but it I believe problem is not caused by it as if I just print out the data using console.log it prints out well. So the problem you be with taking the request or rendering the html i think
Here is the html :
<html>
<head>
</head>
<body>
<form action="example2.js" method="get">
<input type="radio" name="catagory" value="Church"> Church </br>
<input type="radio" name="catagory" value="Piazza"> Piazza </br>
<input type="radio" name="catagory" value="Basilica"> Basilica </br>
<input type="submit" name="Submit"> Submit
</form>
</body>
</html>
And here is the JS document for Node.js
var http=require('http');
var importio = require("import-io").client;
var io = new importio("19781bd4-6f35-405f-88ef-2f3819b42d9c", "T7Twn5JRXweKI9/9bQ5MSdXMpwUTdYsNgFcJQKTj0b8qKea960gm1R/Tf/EMMYhMUzyLVbNFlf1gZ/rLK2bpZA==", "import.io");
var express = require('express');
var app= express();
var bodyParser= require('body-parser');
var data = [];
var runningQueries = 0;
// Make sure that you have connection with import.io
io.connect(function(connected) {
if (!connected) {
console.error("Unable to connect");
return;
}
// Callback for handling the message from import.io
var callback = function(finished, message) {
if (message.type == "DISCONNECT") {
console.error("The query was cancelled as the client was disconnected");
}
if (message.type == "MESSAGE") {
if (message.data.hasOwnProperty("errorType")) {
console.error("Got an error!", message.data);
} else {
console.log("Got data!", message.data);
data = data.concat(message.data.results);
}
}
if (finished) {
console.log("Done single query");
runningQueries--;
if (runningQueries <= 0) {
runningQueries = 0;
console.log(data);
console.log("All queries completed");
for(i=0; i<data.length ; i++){
console.log(data[i].name)
}
}
}
}
//HANDLING REQUEST
app.use(bodyParser());
app.get('/example2.js',function(request, response){
var typeplace = request.body.catagory;
for(i=0; i<data.length ; i++){
if((data[i].name).indexOf(typeplace) === -1){
data.splice(i, 1);
}
}
})
runningQueries += 2;
io.query({
"connectorGuids": [
"e7aecf09-8e0b-449c-9058-60ee01debd3d"
],
"input": {
"webpage/url": "http://www.tripadvisor.com.tr/Attractions-g187791-Activities-Rome_Lazio.html"
}
}, callback);
io.query({
"connectorGuids": [
"e7aecf09-8e0b-449c-9058-60ee01debd3d"
],
"input": {
"webpage/url": "http://www.tripadvisor.com.tr/Attractions-g187791-Activities-Rome_Lazio.html"
}
}, callback);
});
app.listen(8000);
Sorry if my code if unreadable because of hanging parents etc.
Thanks in advance.
It seems you don't have a (GET) route defined for /, at least in the code you've provided.
It seems there is no place in your node js code where you render the "/" page. Since it looks like you are using express already, try the following:
app.get('/', function(req, response) {
response.render('YOUR HTML FORM FILE NAME');
});

Uploading a photo from a form using node.js

I'm quite new to node and need some guidance and help. Before I go any further, I'm trying to do this without any other frameworks like Express. The situation is the following:
I've have a form where a user can upload a photo to a server running in node. The form has the following properties
<form action="/newImages/" method="post" enctype="multipart/form-data">
File goes : <input type="file" name="fileName"><br>
<input type="submit" value="Submit">
</form>
The form input is handled by this code
if (req.method == 'POST' && req.url == '/newImages/') {
console.log("Inside Post method");
var body = ''
req.on('data', function(data) {
body += data
})
req.on('end', function() {
var note = querystring.parse(body)
console.log(note)
fs.writeFile("./test.jpg",body, function(err){
if(err)
{
console.log(err);
}
else
{
console.log("The Picture was saved");
}
})
res.writeHead(302, {
'Content-Type':'text/plain',
'location':'/index.html'});
res.end('Found!');
})
}
However, something tells me I need to parse the data differently, as the output of this is unreadable. It looks like :
"\n\r\n����\u0000\u0010JFIF\u0000\u0001\u0001\u0001\u0000\u0000\u0000\u0000��\u0000C\u0000\b\u0006\u0006\u0007\u0006\u0005\b\u0007\u0007\u0007\t\t\b\n\f\u0014\r\f\u000b\u000b"
Any ideas on how to get this to work? I should also note that I upload .jpg's only.
Thanks
I think that you are wrong when you save your picture. You don't need to use fs.writeFile() but fs.rename.
This cose works in my app.js:
app.post('/upload', function (req, res) {
var tempPath = req.files.file.path,
name = '',
targetPath = '';
fileExist = true;
fileNumber = 0;
var fileType = path.extname(req.files.file.name);
var fileName = path.basename(req.files.file.name,fileType);
while (fileExist) {
fileNumber_str = fileNumber.toString();
var current = fileName + "_" +fileNumber_str + fileType;
console.log("Controllo per "+current);
if (fs.existsSync(__dirname + "/images/orig/" + current)) {
console.log("--> Esiste");
fileNumber++;
} else {
var newPath = __dirname + "/images/orig/" + current;
console.log("nuovo nome : "+newPath);
fs.rename(tempPath, newPath, function(err) {
if (err) throw err;
//Ora creo il thumb
console.log("Upload completed!");
});
break;
}
}
res.redirect("/");
res.end();
});
Take a look.
M.
It seems that you cannot parse multipart data with querystring.parse.
You have to write your own parser or use third-party module, like node-multiparty.
With multiparty module the code will be like this:
if (req.method == 'POST' && req.url == '/newImages/') {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var tmp = files.fileName[0].path;
fs.rename(tmp, '/your/dir/img.jpg', function(err) {
if (err) throw err;
console.log('success');
});
res.end('Found!');
});
}

html5 rocks node js server-sent-events SSE example not working

link to article: http://www.html5rocks.com/en/tutorials/eventsource/basics/
The node.js SSE server is not working in that example. I end up with an open connection to /events, but no response is received by the browser.
sse-server.js
var http = require('http');
var sys = require('sys');
var fs = require('fs');
http.createServer(function(req, res) {
//debugHeaders(req);
if (req.headers.accept && req.headers.accept == 'text/event-stream') {
if (req.url == '/events') {
sendSSE(req, res);
} else {
res.writeHead(404);
res.end();
}
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(fs.readFileSync(__dirname + '/sse-node.html'));
res.end();
}
}).listen(8000);
function sendSSE(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
var id = (new Date()).toLocaleTimeString();
// Sends a SSE every 5 seconds on a single connection.
setInterval(function() {
constructSSE(res, id, (new Date()).toLocaleTimeString());
}, 5000);
constructSSE(res, id, (new Date()).toLocaleTimeString());
}
function constructSSE(res, id, data) {
res.write('id: ' + id + '\n');
res.write("data: " + data + '\n\n');
}
function debugHeaders(req) {
sys.puts('URL: ' + req.url);
for (var key in req.headers) {
sys.puts(key + ': ' + req.headers[key]);
}
sys.puts('\n\n');
}
sse-node.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script>
var source = new EventSource('/events');
source.onmessage = function(e) {
document.body.innerHTML += e.data + '<br>';
};
</script>
</body>
</html>
The problem was with the server. In my case I was using node with IIS using the iisnode node package. To solve this, I needed to configure iisnode in the web.config like so:
<iisnode flushResponse="true" />
After this, everything worked fine. Others with a similar issue may start here, but apache and nginx may have similar configuration requirements.
Why did you comment out the res.end() at the end of the sendSSE function? That's the method that actually sends the response to the browser.
I already try that code and is working for me, as you are not using ngnix, or any other server as proxy for your node instances I would believe that the problem is with your machine, if you have firewall or anti virus running, stop it, and try again or any other software that could be intercepting yours req and res.
Make sure you have saved the HTML file with same name as described sse-node.html in same directory. Other thing might be make sure 8000 port is open in your local machine no one is using it. or change the port and re-run sse-server.js. its working for me as is.
I faced the same issue. Nothing wrong with your code just Provide Full Resource Address in your HTML File.
var source = new EventSource('http://localhost:8000/events'); //true way
instead of
var source = new EventSource('/events'); //improper way

How do I handle CSS with Node.js?

I'm trying to use just straight vanilla Node.js with no frameworks other than what is necessary for educational purposes. I currently have this setup:
var fs = require('fs'),
jade = require('jade');
function compile(dirPath, res) {
var filePath = __dirname + dirPath;
fs.readFile(filePath, 'utf8', function(err, fd) {
var fn = jade.compile(fd, { filename: filePath, pretty: true});
res.write(fn());
res.end();
});
}
exports.compile = compile;
Which is called when the requested page is asked for, like this:
var jadec = require('./jadecompile');
function start(res, postData) {
res.writeHead(200, {"Content-Type": "text/html"});
var cpage = '/staticpages/index.jade',
page = jadec.compile(cpage, res);
}
The page loads great and I get this as my view source:
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<link rel="text/css" href="assets/css/bootstrap.css">
</head>
<body>
<div class="hero-unit">
<p>Hello This Is A Test</p>
</div>
</body>
</html>
But the css doesn't work at all, I've been trying to google it but every answer seems to use express or something else, but I want to learn how to do this as vanilla as possible, so my question is, how can I handle the *.css so that the css is loaded properly, when I click on the href link in the view source, it loads my 404 page, rather than just the plain text of the css file. Thanks!
Feel free to view the repo at: https://github.com/Gacnt/Node-Tests
I managed to fix my problem by creating a function to handle static pages, such as .css or .js, like so:
var http = require('http'),
url = require('url'),
path = require('path');
fs = require('fs');
// ADDED THIS FUNCTION HERE -----------------------------------------------------
function handleStaticPages(pathName, res) {
var ext = path.extname(pathName);
switch(ext) {
case '.css':
res.writeHead(200, {"Content-Type": "text/css"});
fs.readFile('./' + pathName, 'utf8', function(err, fd) {
res.end(fd);
});
console.log('Routed for Cascading Style Sheet '+ pathName +' Successfully\n');
break;
case '.js':
res.writeHead(200, {"Content-Type": "text/javascript"});
fs.readFile('./' + pathName, 'utf8', function(err, fd) {
res.end(fd);
});
console.log('Routed for Javascript '+ pathName +' Successfully\n');
break;
}
}
// ADDED THIS FUNCTION HERE -----------------------------------------------------
function start(route, handle) {
function onRequest(req, res) {
var postData = "",
pathName = url.parse(req.url).pathname;
console.log('Request for ' + pathName + ' received.');
req.addListener('data', function(data) {
postData += data;
console.log('Received POST data chunk ' + postData + '.');
});
req.addListener('end', function() {
var pathext = path.extname(pathName);
if (pathext === '.js' || pathext === '.css') {
handleStaticPages(pathName, res);
} else {
console.log('--> Routing only the view page');
route(handle, pathName, res, postData);
}
});
}
http.createServer(onRequest).listen(4000);
console.log('Server is now listening at: http://127.0.0.1:4000 .');
}
exports.start = start;
In order to handle .css and other static files, there needs to be a file stream in place. Rather than using a switch statement you can just use the following.
var stream = fs.createReadStream(path); //create the file stream
stream.pipe(res); //transfer the file

Categories

Resources