jsreport Hello world - node.js

I'm trying to create my first report with jsreport. I've followed the documentation, but I'm not able to generate the most simple Hello world.
I've tried:
npm install jsreport
and then create a simple server:
var http = require('http');
var jsreport = require('jsreport');
http.createServer(function (req, res) {
jsreport.render("<h1>Hello world</h1>").then(function(out) {
out.stream.pipe(res);
}).catch(function(e) {
res.end(e.message);
});
}).listen(1337, '127.0.0.1');
The server is running on port 1337.
But if I try to open http://localhost:1337/ nothing happens. I was expecting a page with Hello world.
On the server side, I get on the console:
2018-02-17T10:55:16.009Z - info: Initializing jsreport#1.10.0 in development mode using configuration file: jsreport.config.json
2018-02-17T10:55:16.011Z - info: Setting process based strategy for rendering. Please visit http://jsreport.net/learn/configuration for information how to get more performance.
2018-02-17T10:55:16.013Z - info: Searching for available extensions in /home/jgr/WebstormProjects/GeoMasterBoard/server/
2018-02-17T10:55:16.016Z - info: Extensions location cache not found, crawling directories
Do I need a jsreport server running or this code should be enough?
I also tried to install jsreport server, following the documentation.
After jsreport start it shows on the console:
2018-02-17T10:42:46.013Z - info: Initializing jsreport#1.10.0 in development mode using configuration file: jsreport.config.json
2018-02-17T10:42:46.015Z - info: Setting process based strategy for rendering. Please visit http://jsreport.net/learn/configuration for information how to get more performance.
2018-02-17T10:42:46.023Z - info: Searching for available extensions in /home/jgr/WebstormProjects/GeoMasterBoard/server/
2018-02-17T10:42:46.025Z - info: Extensions location cache not found, crawling directories
But nothing happens when I try to open http://localhost:5488/. If I do: nmap -p 5488 localhost the awnser is:
PORT STATE SERVICE
5488/tcp closed unknown
What am I missing?
I'm using node.js v8.1.2, on Ubuntu 16.04.

your code is not working because the following reasons:
when you open your browser at http://localhost:1337/ your browser is actually making 3 different requests (1-> http://localhost:1337/, 2-> http://localhost:1337/favicon.ico, 3-> http://localhost:1337/robots.txt), not just one
the code that your are using to handle the http server is not doing a proper routing, it should process a url just once, right now it is just calling jsreport.render on every single request that goes through your server (even the ones for /favicon.ico, /robots.txt), and this is bad in the browser because as i already explained your browser makes like 3 request for a single page load.
you are using the shortcut jsreport.render in the request handling, which means that jsreport is going to try to initialize itself when your first request arrives, because of the problem explained above (not doing a proper routing in your http server) this results in jsreport trying to initialize 3 times on your first page load which leads to an uncaught exception that exits your process with no error message (we are going to update some things to better handling this exception in the future).
finally, here is some code that completes your hello world test case (with some code that filters unwanted requests like /robots.txt, /favicon.ico, but in production code you should implement a proper router logic in your http server. if you don't want to code it yourself just use something like express)
var http = require('http');
var jsreport = require('jsreport');
http.createServer(function(req, res) {
if (req.url !== '/') {
return console.log('ignoring request:', req.url);
}
console.log('request:', req.url);
jsreport
.render('<h1>Hello world</h1>')
.then(function(out) {
out.stream.pipe(res);
})
.catch(function(e) {
res.end(e.message);
});
}).listen(1337, '127.0.0.1');

Related

force node.exe to go throw proxifier on windows 10

I am developing bots for telegram, I am from Iran and telegram url is blocked in my country and I am forced to use VPN/Proxy servers to access telegram api from my local dev machine.
But I have other apps running on my system that won't work throw a VPN, So I am forced to use proxifier, I can define rules for the apps that I need to go throw a proxy.
But node.exe is ignoring this rules for some reason, I can see in NetLimiter that the connection is coming from C:\Program Files (x86)\nodejs\node.exe, But adding this path to proxifier's rules has no effect, other apps like telegram itself and firefox and ... works fine with these rules ...
So has anyone managed to force node.exe to go throw proxifier?
I also tried to setup a proxcy with php in my host, but none of the proxy scripts I found was able to handle the file uploads
My last hope is to install some modules for apache and use it as a proxy or just install nginx ...
I also tried https://github.com/krisives/proxysocket and https://github.com/TooTallNate/node-https-proxy-agent with no success, its just keeps throwing errors :(
Ok, after hours of trying finally got this to work with proxifier.
https://github.com/TooTallNate/node-https-proxy-agent
new HttpsProxyAgent('http://username:password#127.0.0.1:8080')
Update :
This approach had its problems so I created a small personal proxy server with node-http-proxy on my server and connected to it:
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
const debug = require('debug')('app');
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({
secure : false
});
proxy.on('error', function (e) {
debug(e);
});
const server = http.createServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
proxy.web(req, res, { target: 'https://api.telegram.org', });
});
server.listen(3333);
And simply just redirected all the request to this server.

Display text file using node js from a remote server

Good day! I'm having a hard time fixing this issue. I'm currently using node js webserver (http).
I'm a beginner in using node js so any help would be appreciated.
What I'm hoping to achieve is to display a string 'Hello World!' in the browser while accessing it through the URL. The problem is I'm running the script from a remote server and unfortunately I can't access it through the URL.
The script is running fine but for the browser it returns an error saying:
host didn’t send any data.
ERR_EMPTY_RESPONSE
Here is the script I'm running from the remote server:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Hello World!');
response.end();
}).listen(2000);
I think my script doesn't have a problem. So I'm guessing it's from the setup of the server, but I don't have any idea in which part it's causing not to display it. I'm currently using a Linux Server.
Thanks in advance!
From what I can see you are listening on port 2000, are you sure that the url you are requesting the data from also contains the port e.g http://localhost:2000/ ?? Browsers by default tries to connect using port 80 on http and 443 for https, if you are listening on a different port than those, you have to define it in the url, by using a ":" after the domain/ip address
Anyway, have a look at the express module for server side rest APIs, will make request handling so much easier:
const express = require('express');
const app = express().listen(80);
app.get("/",function(request,response){
response.send('Hello World');
});
Express allows you to handle the creation of web servers better.
But node or express, do make sure that the URL you have entered consists of the port number that you have asked the server to listen to.
Another possibility is that the port you have asked to display your response is already being used by another server. You can try using a different port number.
You might have gotten the answer, but this is for the folks out there who are new to node at present and have stumbled upon this stackoverflow question! Good day :)

Streaming from NodeJS server not working when access from outside

I have a question about streaming an audio file via a NodeJS server. I'm using the following code:
var http = require('http');
var fs = require('fs');
var filePath = 'media/test.mp3';
var stat = fs.statSync(filePath);
http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
fs.createReadStream(filePath).pipe(response);
})
.listen(3000);
It does work when I ...
run it locally: http://localhost:3000 or
run it on a different machine in the same network: http://192.168.1.42:3000.
But it does not work when I ...
run it from outside, e.g. calling http://my-public-ip:3000 or
using a DynDNS service: http://my-dyndns-provider.com:3000.
By not working, I mean I can see a pending request ("request is not finished yet!") in Chrome devtools, but the stream sometimes starts only for less than a second, sometimes it doesn't start at all. In the devtools I can see that only 4 KB are loaded (on localhost it's 3.1 MB).
To enable the access from outside, I configured port forwarding on my router, so that requests to port 3000 are forwarded to my computer's internal IP.
For other things than streaming my setup is working, so for example it is possible to call REST routes defined on the server.
EDIT:
Meanwhile, I also tried to do the streaming with PHP instead of NodeJS. But it shows exactly the same behaviour.
Do you guys have an idea what could be the reason?
Thank you!
Looks like some configuration issue with setting up port forwarding in router as you have tried with two different code bases.
If you are doing only for testing you can use localtunnel to expose your localhost to publicly over the internet.
There are few other alternatives also like ngrock or forwardhq.
Hope it helps.
Yesterday, I finally was able to test the exact same setup but with a different router (FritzBox 7320) -- and everything worked as it should. So there must be problems with the router I'm using at home (o2 HomeBox 6441).
I think the best will be trying to get some support in the manufacturer board.
Thanks for your effort anyways!

Streaming large files causing server to hang

I have a feature in my web app that allows users to upload and download files. I serve up the app with Express, but the files are stored in a different server, so I proxy the requests to that server. Here's the proxy code using the request library:
module.exports = function(req, res) {
req.headers['x-private-id'] = getId();
var url = rewriteUrl(req.url);
var newRequest = request(url, function(error) {
if (error) console.log(error);
});
req.pipe(newRequest).on('response', function(res) {
delete res.headers['x-private-id'];
}).pipe(res);
};
This works fine for all of my requests, including downloading the file. However, I run into issues when 'streaming' the file. And by streaming, I mean I use fancybox to display the video using a video tag. The video displays fine the first few times.
But if I close fancybox and then reopen it enough times (5 specifically), it quits working after that; the video no longer shows up. The entire Express server seems to hang, unable to process any more requests. If I restart the server, everything is OK. To me it seems like the sockets from the proxy requests aren't being closed properly, but I can't figure out why. Is there something wrong with my proxy code?
You need to either increase the pool.maxSockets value passed in the request() config since it defaults to node's HTTP Agent's maxSockets which is 5, or opt out of connection pooling altogether with pool: false in the request() config.

some questions from a node.js newbie

i have just started learning node and i am using node-v0.4.11 on Fedora 12. It installed without any errors and i am able to run some basic programs but there are some things i cant figure out
If i create a server at a port and then if i stop node using Ctrl+C
i cannot use that port again for starting a server without restarting
the system.
my code looks like this
var port=8080;
var count=0;
var http=require('http');
var server = http.createServer(function(req, res) {
count++;
console.log('request no '+count+' received');
res.writeHead(200);
res.end('you are at port '+port);
});
server.listen(port);
console.log('server started at port '+port);
Now when i save the file and execute it the server starts. But when i stop the server from the shell , i cannot start the server again at the port i started before(in this case port 8080).This is bad because every time i have to make changes in that file i have to change the port number too.Can i stop this behavior?
EDIT:
This is the error that i get when i try to start the server at the same port again
Server started at 8080
node.js:203
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: listen EADDRINUSE
at errnoException (net_uv.js:557:11)
at Array.<anonymous> (net_uv.js:632:28)
at EventEmitter._tickCallback (node.js:195:26)
i saw the process list after i terminated node using Ctrl+C and i found node was still running. So i killed it and checked the process list again to make sure it was dead and it was(i could not see it in the process list). Now i again tried to start the server at the same port but i got the same error as above.And once i stop the server and make request from the browser the request hangs up for ever(it keeps on waiting).
My next problem is that in the above when the server starts and i make
the first request count is incremented 3 times and i can see 3
messages at the console. This is just for the first request,if i make
more requests count is just incremented once. Whats wrong?
this problem is solved
My next problem is that if i change res.writeHead(200); to
res.writeHead(404); or any other valid status code like 300 node
gives error at the command line but these are valid status codes and
the server should start and respond to each request according the
status code like Not found for 404. What am i doing wrong?
this problem is solved
I am not able to use Firebug's 'Net' tab to monitor requests when i
send requests to the server created by Node. Is there a way to do so?
Thanks for bearing.
i cannot start the server again at the port i started before
You should not be seeing this behavior, and I cannot reproduce it. Do you get an error message when you try to start the server again? What is it? Once you've stopped the server, do you see any node processes in your process list? If so, can you start your server after you kill them?
count is incremented 3 times and i can see 3 messages at the console
Your browser is sending multiple requests. For example, in Chrome, you might get (1) a pre-fetch request (where Chrome downloads the page it thinks you want), (2) the actual page request, and (3) a request for favicon.ico; your Node app is listening for all requests, not just requests to the / URL. After the initial request, the browser caches the favicon, etc. and doesn't need to request them again.
Try adding console.log(req.url); to your callback and see what URLs the browser is asking for.
any other valid status code like 300 node gives error at the command line
I can't reproduce this problem. What error are you receiving?
I am not able to use Firebug's 'Net' tab to monitor requests when i send requests to the server created by Node
I'm also not able to reproduce this. Firebug and other client-side debugging tools don't know or care what technology is running on the server; it just speaks HTTP.

Resources