error function is not defined for res node - javascript

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.

Related

How do I use Node functions and variables from HTML while using a server?

I'm trying to build a few programs that execute Node.js functions from HTML (e.g you press a button and some code using Node.js runs).
Here is the code I'm using to display the HTML
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
(Too long for a comment.)
First you must decide whether pressing a button shall
lead to a complete new HTML page that contains the results of the Node.js code execution or
update only parts of your existing HTML page.
In the first case, sending back static HTML pages (as your code does) will not be sufficient, you would need a template engine.
In the second case, you need client-side Javascript code to fetch JSON data (say) from your server and update the DOM of your HTML page.

NodeJS Error: Can't Find Variable: require

I am working with a NodeJS server that hosts a website and a Javascript program. Most of the javascript works fine, but I am running into an error now with one of the npm modules that isn't able to be "required".
I'm getting an error from the inspector console that:
ReferenceError: Can't find variable: require
I am not sure what's happening here, as from what I can tell the server should have access to these public modules. Here is the server code:
var fs = require('fs');
var http = require('http');
http.createServer(function(request, response) {
if(request.url === "/Users/christophermartone/Desktop/Programing/resturauntApp/driver.js") {
var file = fs.createReadStream('driver.js');
file.pipe(response);
console.log("Made it to JS");
response.writeHead(200, {'Content-Type': 'text/javascript'});
}
else {
var file = fs.createReadStream('index.V1.0.html');
console.log("Made it to HTML");
file.pipe(response);
response.writeHead(200, {'Content-Type': 'text/html'});
}
}).listen(8080);
I found some documentation that suggested I should do npm link #Source/Module... which I did, but the issue is still not resolved.
Am I missing something in the server script? Or is there an extra step I am missing?
I can provide the full html and javascript code if needed, but the issue does not appear to be with them, only when they are running on the Node server.

How to call node.js server javascript from html page

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.

how to read file using fs in node app?

I'm tring to read this file in nodejs using fs module.
I'm getting the response twice. let me know what am i doing wrong. Here's my code.
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res) {
fs.readFile('sample.txt', function(err, sampleData) {
console.log(String(sampleData));
//res.end();
});
console.log("The end");
// res.writeHead(200);
res.end();
}).listen(2000);
After hitting the port in browser. I'm getting the response twice in my terminal. Here's the output.
The end
this is sample text for the testing.
The end
this is sample text for the testing.
You are most likely getting it twice because you are accessing http://localhost:2000/ from the browser.
When doing so there are actually two requests being made. Your actual request and the favicon :) both of which are handled by your server.
Have a look into Chrome debugger -> Network
Two log messages will appear: one for / and one for /favicon.ico
You can verify this by adding console.log(req.url);
To avoid this:
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res){
if(req.url === '/'){ // or if(req.url != '/faicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
// res.writeHead(200);
}).listen(2000);
A request is made to favicon.io automatically.
To avoid automatic request to favicon, you can do the following
http.createServer(function(req, res){
if(req.url != '/favicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
}).listen(2000);
O/p =>
The end.
this is sample text for the testing.
You may pipe the file to the client:
fs.createReadStream('sample.txt').pipe(res);

Setting a document root to your Node.js http server?

I just setup a basic node.js server with socket.io on my local machine. Is there a way to set a document root so that you can include other files. Ie. Below I have a DIV with a a background image. The path the image is relative to the location of the server, however this is not working. Any ideas? Thanks!
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<div style="background-image:url(img/carbon_fibre.gif);"><h1>Hello world</h1></div>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
Use Express or Connect. Examples: https://github.com/spadin/simple-express-static-server, http://senchalabs.github.com/connect/middleware-static.html
For the background-image style, browser will create a entirely new HTTP Request to your server with path *img/carbon_fibre.gif*, and this request will certainly hit your anonymous function, but your response function only write back a div with ContentType: text/html regardless the req.pathname so that the image cannot be properly displayed.
You may add some code to your function like:
var http = require('http'),
io = require('socket.io'),
fs = require('fs'),
server = http.createServer(function(req, res){
// find static image file
if (/\.gif$/.test(req.pathname)) {
fs.read(req.pathname, function(err, data) {
res.writeHead(200, { 'Content-Type': 'image/gif' });
res.end(data);
});
}
else {
// write your div
}
});
server.listen(8080);
I'm not very familiar with nodejs, so the code above only demonstrates a logic but not the actual runnable code block.

Categories

Resources