AJAX call with Express - javascript

I am trying to append HTML dynamically with Express framework in a static HTML file that my server serves. I've found about the cheerio module that does exactly what I want, but I was wondering if there is a much cheaper way for the system instead of loading the whole HTML and appending a string.
I searched about AJAX and how to communicate with the client but I didn't manage to make it work. The code I am using with cheerio is:
exports.modify = function(req, res){
var html = fs.readFileSync(__dirname + '/../public/index.html', 'utf8');
var $ = cheerio.load(html);
var scriptNode = '<p>Source code modified</p>';
$('body').append(scriptNode);
fs.writeFile(__dirname + '/../public/index.html', $.html(), function (err) {
if (err) throw err;
console.log('It\'s modified!');
});
res.send($.html());
};
How can I do it in more 'proper' way (maybe with AJAX call)? Any suggestions would be more than welcome.

Assuming you want to handle JSON as a data type then you can setup another specific route or you can filter the request type within the current route handler :
exports.index = function(req, res) {
var data = someData.fetch();
switch(req.format) {
case 'json':
res.json(data);
break;
default:
res.render('template', {
data:data
});
}
};

Related

Using base64 function results in InvalidCharacterError

What I want to do is using base-64 module method, in my node.js + express project.
The code is like this.
router.get('/list', function(req, res, next) {
client.query('SELECT * FROM Document',function(err, row){
if(err) throw err;
var base64 = require('base-64');
row.forEach(e => {
e.text = base64.decode(e.text);
});
res.render('main/list',{title:"###", row:row});
})
});
In this function, there are MySQL query in the callback.
The text is the base-64 encoded value of the Database.
But, the base64.encode() doesn't work in this code, but results in InvalidCharacterError
how should I use correctly?
You can use nodejs built-in functions
let original = 'abcdefrgsdfdsf123123123123';
let testCode64 = Buffer.from(original).toString('base64')
let testDecode64 = Buffer.from(testCode64, 'base64').toString('utf-8');

Pass variable to html with NodeJS

I made a listing of files that exist in a particular folder, I would like that after listing, it would be possible to access this variable in HTML.
Server.js
var http = require('http');
var arquivo = require('fs');
var server = http.createServer(function(request, response){
response.writeHead(200, {'Content-Type': 'text/html'});
arquivo.readFile(__dirname+'/pagina.html',
function(err, html){
if (err) {
response.write("Arquivo não encontrado!");
response.end();
} else{
response.write(html);
var fs = require('fs');
var files = fs.readdirSync(__dirname+'/list/'); //LIST FOLDER
response.end();
}
});
});
server.listen(3000, function(){
console.log('Servidor está rodando!');
});
pagina.html
<html>
<script type="text/javascript">
alert(files); //Name of var list
</script>
</hmtL>
Replacing a raw string with a variable has several clean solutions. I would recommend any of the following:
handlebars
ejs
hogan
There are two ways to do this.
separate your call into another endpoint on your server and make a request on the client (recommended since you will need this later probably)
use regex to change your html file (fun experiment)
imagine your html file looks like this; notice the double brackets.
"<html><body><script> var files = {{myvars}} </script></body></html>"
and you have a list of files in an array
var yourFiles = ['file1', 'file2', 'file3']
you can then use regex to fill in the variables in the original html string
var newHTML = html.replace('/\{\{myvars\}\}/', JSON.stringify(yourFiles))
response.write(newHTML);
response.end();
the final html sent will look like this
"<html><body><script> var files = ['file1', 'file2', 'file3'] </script></body></html>"

JavaScript return not working as expected

This is a total newbie questions, and I'm trying to learn JavaScript and node.js. I'm attempting to use request to grab information from an api, and then store the information in an array that I can then manipulate.
Here is my code so far:
const request = require('request');
var url = "https://www.predictit.org/api/marketdata/ticker/CHINA.INAUGURAL.2017";
var info = request(url, function(err, res, body){
var json = JSON.parse(body);
return json;
})
However, the info variable seems to only store something that I think is related to the request call, but I'm not sure. If I replace return json with console.log(json) then it prints the array immediately, though I can't get it to store it.
I would like to tell node info['ID'] and have it return 2835
Node does not work like this. Node is asynchronous.
You can try this,
var info;
request(url, function(err, res, body){
info = JSON.parse(body);
});
Looks like you' re requesting xml file from that url. You can install xml2js library for nodejs by typing npm install xml2js and let it parse the xml for you. After that
var parseString = require('xml2js').parseString;
var url = "https://www.predictit.org/api/marketdata/tick /CHINA.INAUGURAL.2017";
var info = request(url, function(err, res, body){
parseString(body, function (err, result) {
info = JSON.parse(JSON.stringify(result));
});
return info;
})
I hope this one should work,
request('https://www.predictit.org/api/marketdata/ticker/CHINA.INAUGURAL.2017',
function (err, res) {
if (err) {
console.log('ERROR: Something went wrong');
}
else {
parseString(responce.body, function (err, result) {
res.json(result);
});
}
});
I think that data is stored into 'info' variable but you're using it before data is stored.
Here it takes some time for API call to process and get data. Then it will be stored into 'info' variable. Have a timeout of 5s and then try console.log(info[1]) and would return expected value.
This is due to asynchronous nature of nodejs. Here your code might be executing info[1] before it is set by API call.

How to use Node.js to read data from a json file and display the read data into html?

I am a complete newbie and just did something like this:
var fs = require('fs');
var file = __dirname + '/data.json';
var http = require ('http');
var server = http.createServer(function (req, res){
res.writeHead(200);
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
res.end(data);
});
});
server.listen(8000);
When I am doing:
data = JSON.parse(data);
console.dir(data);
Instead of
data = JSON.parse(data);
res.end(data);
It is able to display the data I have in .json on the console. However when I am trying to create a server and post the data using res.end, it doesn't really work.
Could someone offer some insights? Is it because the "data" I have here is only an object? How should I process the data I get from .json in order to use for my html?
The http module doesn't support Objects as a response (it supports buffers or a strings) so you have to do this:
res.end(JSON.stringify(data));
however if used express you could do this
res.send(data);
Since the file is already in the right format, you can simply pipe it to the response.
var fs = require('fs');
var file = __dirname + '/data.json';
var http = require ('http');
var server = http.createServer(function (req, res){
res.writeHead(200, {'Content-Type': 'application/json'});
fs.createReadStream(file, 'utf8').pipe(res);
});
server.listen(8000);

Node.JS where to put the response.end()

I'm developing a simple NODE.JS application. First I create an httpServer using http module. Then I route the request to the requestsHandlers.js page. 'Response' parameter cames from the creation of the httpServer. Process1, process2 and process3 should write an answer to the page. This is the objective of this app, that process1, process2 and process3 write its respective text.
requestHandlers.js
var process1 = require("./process1");
var process2 = require("./process2");
var process3 = require("./process3");
function iniciar(response) {
console.log("Manipulador de petición 'iniciar' fue llamado.");
response.writeHead(200, {"Content-Type": "text/html"});
process1.fc1(response);
process2.fc2(response);
process3.fc3(response);
//response.end() //WHERE DO I PLACE IT?
}
As you can see, the response parameter is passed to process1.js, which after parsing some data shoud echo some information.
process1.js
var request = require('request')
function fc1 (response){
var url = 'http://webpagethatreturnsJSONfile.com/'
//Download webpage data and parses it
request(url, function(err, resp, body) {
if (err)
throw err;
var jsonResult = JSON.parse(body);
response.write("Number:" + jsonResult.number + '');
//response.end() //WHERE DO I PLACE IT?
});
}
exports.fc1 = fc1;
The point is that I don't know where to put 'response.end()'. Each process takes some time and I want to 'end' when all processes have echo their text.
How could I do it?
I don't know if the code I've attached is enough for helping me.

Categories

Resources