Situation
I have a html page which calls multiple javascript files. Everything works on client-side right now.
Because I need to execute a jar within javascript, I am switching to Node.js. (applets are deprecated)
However, I am new to node.js and confused about how to link everything.
I have :
index.html which calls various .js scripts (files.js,objects.js,etc.)
webServer.js which makes the node.js server
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
javaApp.js which executes a jar
var exec = require('child_process').exec;
var child = exec('java -jar E:/JavaApp.jar',
function (error, stdout, stderr){
console.log('Output -> ' + stdout);
if(error !== null){
console.log("Error -> "+error);
}
});
module.exports = child;
The question
I would like, when clicking on a button in my html, to call javaApp.js on the server side.
I know Express can be used to link index.html to webServer.js, but I don't understand how to link index.html to the code used by the server.
i.e. How can I call javaApp.js from index.html if there's no function name in it?
Is this answer relevant ? How to call node.js server side method from javascript?
If you want to call the jar on the server you have to create a route for it(maybe using express).
router.get('/call-java-app', function (req, res, next){
//call you function in here
//respond with any data you want
res.send('Your data here');
});
Your button would have to make a get request at /call-java-app and optionally wait for any response from the server.
var url = '/call-java-app';
console.log(url);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4) {
//handle server response here if you want to
}
}
xmlHttp.open("GET", url, true); // false for synchronous request
xmlHttp.send(null);
How can I call javaApp.js from index.html if there's no function name in it?
You can't. At least not sensibly.
Change it so it exports a function you can call if you want to call it multiple times.
Since it is asynchronous, you should make that function return a Promise.
In your webserver, require the module you write to get access to the function it exports.
Write a route which calls that function and returns a suitable HTTP response.
Then cause the browser to make an HTTP request to that route by clicking a link, submitting a form, using fetch, or whatever other method you like.
Your webserver is now as simple as it (almost) can be. Just sending index.html when the ip+port 8080 is called with http (get).
Before you can use your jar-module you have to make a requiere in your webserver:
var child = require('javaApp')
This will give you access to "child" wrappet with a error-function. What "child" actual is doing and can do, you probably know (i hope). If you skip the index.html you can send some response from your "child" to see how it works.
Related
Say I have this code in node.js:
app.post('/stuff', function(req, res){
res.send('hello world');
});
app.route('*').all(function(req,res,next){
res.write('Hello World');
});
There are 2 routes here - one is a catch-all for any request to the server and the other is what to do if a post request with a route of /stuff is sent.
Is it possible to pass a value local to the post request into route?
Intended Program flow: initial request to the server goes through route (which has controls not illustrated to ignore post requests) and the connection is left open, then a post request is sent from the initial request and is dealt with by app.post - can a value found within the closure of post be passed to the initial request that is still open?
I am trying to avoid using Global variables, and res.local only has a local scope. Also trying to keep clean so if I can use native express or node.js all the better. Much obliged for any help.
then a post request is sent from the initial request
Why don't you simply pull out the POST function and call it from both handlers, that way you don't need to send a seperate request from inside your app.
var postHandler = function(req, res) {
res.send('hello world');
// Just return whatever you want back to the calling function
return someValue;
};
// Set it as the handler for post.
app.post('/stuff', postHandler);
app.route('*').all(function(req,res,next){
// Call function.
var returnValue = postHandler(req, res);
res.write('Hello World');
});
app.route('*').all(function(req,res,next){
if (req.originalUrl === '/stuff') {
req.variable = 'some value';
return next();
};
res.write('Hello World');
});
app.post('/stuff', function(req, res){
var value = req.variable;
res.send('hello world');
});
You can try this code. Please take the order of app.all and app.post.
The second way, your can try app.locals http://www.expressjs.com.cn/4x/api.html#app.locals
The app.locals object is a JavaScript object, and its properties are
local variables within the application.
I've been looking over this basic example in order to set up a simple server in Node, however I am really struggling to understand where the 'request' and 'response' parameters are coming from. Where do they point to and how?
// Load the http module to create an http server.
var http = require('http');
function onRequest(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
}
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(onRequest);
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
Usually when passing paramaters into a function I pass something I can see, like a variable equal to 5, or 'Hello', but in this case I'm not...
Sorry if this is not explained very well!
When you call createServer, you are passing the function onRequest to it:
var server = http.createServer(onRequest);
This pattern is known as a callback: you pass a function to someone else, with the expectation that they will call your function if something interesting has happened.
In essence, you are saying to Node,
Hey, please create an HTTP server for me. Whenever you receive a request, call my function onRequest with the request and response objects passed as parameters.
Another way to do this is to listen to the request event, which takes the same parameters in its callback.
The parameters are documented as being http.IncomingMessage and http.ServerResponse. You can call them whatever you want, but request and response are the idiomatic parameter names. (Some people use req and res because they are shorter to type.)
Create server and send response :
1).Create server
var http = require('http');
var server = http.createServer ( function(request,response){
response.writeHead(200,{"Content-Type":"text\plain"});
response.end("Hello");
});
server.listen(8000);
console.log("Server running on port 8000");
2).Save above code and run in cmd .
3).Open browser and go to http://localhost:8000/
Now you see the "Hello"
I am new with node and I am trying to print the results to the console and eventually display them in HTML. I have tried invoking the function as a var that I would later use in HTML but this didn't work. Some similar example code:
var app = require('express')();
var x = require('x-ray')();
app.get('/', function(req, res) {
res.send(x('http://google.com', 'title').write());
})
Thanks!
I don't know much about the "x-ray" library, but I presume the problem is with that since it has to asynchronously make a request before it can return the response data. The documentation says that if you don't set a path as an argument to the write function it returns a readable stream, so try this:
app.get('/', function(req, res) {
var stream = x('http://google.com', 'title').write(),
responseString = '';
stream.on('data', function(chunk) {
responseString += chunk;
});
stream.on('end', function() {
res.send(responseString);
});
});
You also need to start the server listening on a particular port (3000 in the example below):
const PORT = 3000;
app.listen(PORT, function() {
console.log("Server is listening on port " + PORT + ".");
}); // the callback function simply runs once the server starts
Now open your browser and navigate to 127.0.0.1:3000 or localhost:3000, and you'll see "Google" appear!
ALSO: If you want to use the response data in a full HTML page (rather than just sending the string on its own), you may want to explore further how to do this in Express with Jade (or similar) templates. And the code at the moment scrapes Google every time someone makes a request to the appropriate route of your server; if you only want to scrape Google once, and then use the same string again and again in your server's responses, you may want to think about how to implement this (it's easy!).
I use the following code and when I run the program which is run this function I got error res is not defiend(TypeError: undefined is not a function),what It can be ?I have it in the function params???
http.createServer(function (req, res) {
res.redirect("http://localhost:3002");
}).listen(9006);
https://github.com/nodejitsu/node-http-proxy
There I use the
Setup a stand-alone proxy server with custom server logic
undefined is not a function means redirect is not a function (or method) of res. I'll bet you if you do console.log(res), you won't get an error, which means that, yes, res is defined, but redirect is not. It is an ExpressJS method, so I assume you haven't require'ed Express is your app, if you were planning to use it.
If you want to redirect without Express, one option is to set a different location header and response code (from here):
response.writeHead(302, {
'Location': 'your/404/path.html'
//add other headers here...
});
response.end();
From Wikipedia:
The HTTP response status code 302 Found is a common way of performing
URL redirection.
Edit
According to the library you've provided:
You may send a response page using what #Josh wrote or you may also handle the 404 page at the same time with the following code:
var http = require('http'),
fs = require('fs'),
util = require('util'),
url = require('url');
var server = http.createServer(function(req, res) {
if(url.parse(req.url).pathname == '/') {
res.writeHead(200, {'content-type': 'text/html'});
var rs = fs.createReadStream('index.html');
util.pump(rs, res);
} else {
res.writeHead(404, {'content-type': 'text/html'});
var rs = fs.createReadStream('404.html');
util.pump(rs, res);
}
});
server.listen(8080);
NodeJs don't have any redirect function use following code for redirect
res.writeHead(302, {
'Location': 'http://localhost:3002'
//add other headers here...
});
response.end();
Note TypeError: undefined is not a function means that function you trying to access is not defined.
I've recently ran into a very interesting problem while writing a web app with node.js.
Essentially, all I am doing is serving the index.html page to the client.
Here is the code:
var http = require('http');
var url = require('url');
var fs = require('fs');
var util = require('util');
var server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
if(path == '/'){
console.log("LOADING INDEX...");
openIndex(req, res);
console.log("LOADING COMPLETE.")
} else {
res.write("Something went wrong...");
res.end();
}
}
);
var openIndex = function(req, res){
fs.readFile('./index.html', function(error, content){
if(error){
res.writeHead(500);
res.end();
}
else{
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(content, 'utf-8');
}
});
}
I've put some debugging statements just before and after the index.html page loads: "LOADING INDEX..." and "LOADING COMPLETE".
Now, I have shared the link to my server with my Facebook friends so they can see my app. Most of the time, everything works as it should, but once in a while I get this error:
LOADING INDEX...
This type of response MUST NOT have a body. Ignoring data passed to end().
and just now I've also gotten:
LOADING INDEX...
This type of response MUST NOT have a body. Ignoring write() calls.
The process never raches the "LOADING COMPLETE" statement.
I've tried to reproduce this countless times (accessing my app on different machines, browsers, devices, OS-versions) but every time it works as it should.
I've looked around for other people having this problem, and it seems that somehow, a body is getting into a GET response? I'm not entirely sure what this means or how to fix my code to prevent that from happening. Also, I'm not sure what the clients that produce this error see? Do they get to see my app? (i.e. are these just warnings and as far as they are concerned everything is fine?)
Any help with this will be greatly appreciated.
Xaan
If you're just using a static index.html, why not use express.static to serve it automatically?
app.use("/index.html", express.static(__dirname + '/index.html'));
This would cause expressjs to automatically handle HEAD requests, which should solve your problem.