When I try to start following script:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8000);
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log(ip)
I get following Error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
ReferenceError: req is not defined
at Object.<anonymous> (/home/ubuntu/IPDeliverer/server.js:9:10)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:32)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:41)
My first guess was, that there is some module missing, so I installed the following module like this:
npm install req
and then I included following line
var req = require("./node_modules/req/node_modules/request");
but it is still not working. Any suggestions ?
You've named the Request request, not req, also every callback has it's own request, so checking the IP outside the callback like that doesn't make sense. Use request inside the callback instead:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
console.log(ip)
}).listen(8000);
The variable req is not defined there. You have to move it inside of a request handler. Try this:
var http = require("http");
http.createServer(function(request, response) {
var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
console.log(ip)
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8000);
Related
To show my students a simple HTTP request and response that they could capture using Wireshark, I whipped up a simple Node.js HTTP server:
var fs = require('fs');
var http = require('http');
var port = 80;
var file = process.argv[2]; //This file contains a 42 byte HTML page
http.createServer(function (req, res) {
res.writeHead(200, { 'content-type' : 'text/html' }); // Sends first packet
fs.createReadStream(file).pipe(res); // Sends second packet
}).listen(port);
Unfortunately, the two lines transmitting the HTTP header and the HTML are sent as two separate TCP packets (even though they are both quite small). It would be simpler for my students if the HTTP header and HTML were just one packet. How could I change my code to do this?
var http = require('http');
var fs = require('fs');
var file = process.argv[2];
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html;"});
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
response.write(html);
response.end();
});
}).listen(8000);
the reason it won't work is that Node.js runs everything asynchronously. When you are loading your html file, the server creation starts the same time. By the time you are about to write your html to your tcp socket, the file most likely won't be ready.
I see what you were trying to do before... I misread your code because of the indentation. Let me know if this snippet works.
try using something like-
var file = process.argv[2];
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});
As the title says, I have a problem with what node.js command prompt says lies in the requestHandlers.js file. I am following the guide in the Node Beginner Book and until now, there have not been any problems with the book - or rather my code.
I have the following input:
index.js:
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
server.js:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
router.js
function route(handle, pathname) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname]();
} else {
console.log("No request handler found for " + pathname);
}
}
exports.route = route;
requestHandlers.js
function start() {
console.log("Request handler "start" was called.");
}
function upload() {
console.log("Request handler "upload" was called.");
}
exports.start = start;
exports.upload = upload;
And I have this output:
"C:\Program Files (x86)\nodejs\requestHandlers.js:1
console.log("Request handler "start" was
SyntaxError: Unexpected identifier
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:\Program Files (x86)\nodejs\index.js:1:153)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)"
I can't really see where the problem lies. I have followed the guide in the book and I have either copy-pasted the code from the book or written it myself. I have doublechecked the code for errors, but have not found any. I have remembered to use \'function\' for instance, so there would not be any mistakes in the code when entering it in node.js.
So any help would be appreciated!
Thanks.
You're mixing the different string markers in JavaScript.
function start() {
console.log("Request handler "start" was called.");
}
function upload() {
console.log("Request handler "upload" was called.");
}
You can use " for the start and end of a string, but something like "Request handler "start" was called."
Is invalid, because you terminate the string at "start and start a new string at "was called.
If start and upload are variables just concatenate the strings with something like this:
"Request handler " + start + " was called."
or change your string to something like this:
"Request handler 'start' was called."
or remove the " around start and upload.
i am facing some error in developing chat server client on linux please help
var http = require('http');
fs =require('fs');
var app = http.createserver(function (request, response)
{
enter code herefs.readfile("client.html",utf-8,function(error,data)
{
response.writehead(200,{'content-type': 'text/html'});
response.write(data);
response.end();
})
}).listen(1337);
io.sockets.on('connection',function(socket)
{
socket.on('message_to_server',function(data)
{
io.socket.emit("message_to_client",{message: data["message"]});
});
});
// at Object. (/home/aashish/chatbox/main.js:5:16)
error
it's createServer where S is an uppercase letter
createServer() is now deprecated meanwhile you could use Server() instead .. just check the following snippet or simply use express web framework.
var http = require("http");
var server = http.Server(function(request, response) {
response.end("heeloo world");
});
server.listen(3030, function(err){
if(!err)
console.log("success");
else
console.log("error");
});
var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
this writes to console on a request from my chrome browser:
Request received
Request received
Two times? Why?
It was your browser asking for favicon.ico
i am new to Node.js. i followed the tutorial and typed the following
var sys = require("util"),
http = require("http");
http.createServer(function(request, response) {
response.sendHeader(200, {"Content-Type": "text/html"});
response.write("Hello World!");
response.close();
}).listen(8080);
sys.puts("Server running at http://localhost:1331/");
but when i go to my browser and type the url i.e. http://localhost:1331
it is failed to open th erequested URL
getting the following in cmd when browse the URL
TypeError: Object #<ServerResponse> has no method 'sendHeader'
at Server.<anonymous> (D:\node_js\hello.js:11:14)
at Server.emit (events.js:70:17)
at HTTPParser.onIncoming (http.js:1511:12)
at HTTPParser.onHeadersComplete (http.js:102:31)
at Socket.ondata (http.js:1407:22)
at TCP.onread (net.js:354:27)
It looks like you followed an out of date tutorial. The Node API has since changed. Try this example:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('Hello World\n');
}).listen(1331);
console.log('Server running at http://127.0.0.1:1331/');
It looks like you're listening on port 8080. Either change your URL or the port number you're passing into listen().