I'm trying to make a local server using nodeJs but its not working.
What is tried
var http = require('http');
http.createServer(function(req, res) {
res.write('Hello');
req.end();
}).listen(8080);
Be careful when using response.end!
What is the difference between response.end() and response.send()?
response.end() will always send an HTML string, while response.send() can send any object type. For your example, both will serve the purpose since you are sending an HTML string of 'hello', but keep these cautions in mind as you proceed to build your server!
var http = require('http');
//Example with response.end()
http.createServer(function(request, response) {
response.end('Hello');
}).listen(8080);
//Example with response.send()
http.createServer(function(request, response) {
response.send('Hello');
}).listen(8080);
//Example with res.send() object
http.createServer(function(request, response) {
response.send({ message: 'Hello', from: 'Happy Dev' });
}).listen(8080);
The res (which stand for response) in the callback is a Stream. After you write all you want (headers, body) to the stream, you must end it like so:
res.end();
What you have is req.end().
Using req instead of res was your error.
Also, since you only write one line in this contrived example, you could write the buffer and end the stream in one go:
const server = http.createServer(function (req, res) {
res.end('Hello');
});
server.listen(8080);
Docs for response.end
Related
I am a beginner to node.js and i did a sample code it shown below,
var http = require("http");
var server = http.createServer(function(request,response) {
response.writeHead(200, {
"content-Type" : "text/html"
});
response.end("Hello again");
}).listen(8888);
and when i run this file on eclise Run as ------> Node project
and when i open the browser with url localhost:8888 it shows web page not availble. can u guys help me to find out. I already installed node.js on my system and npm alse. am i missing something?
There is no request or response object in the scope of your request callback. You need to define them as arguments of the callback function.
var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {
"content-Type" : "text/html"
});
response.end("Hello again");
}).listen(8888);
You should definitely get an error though - are you sure your IDE is set up properly?
You never accept the "request" variable. Below is a working version of what you're attempting.
var http = require("http");
var server = http.createServer();
server.on('request', function(request, response) {
response.writeHead(200, {
"content-Type" : "text/html"
});
response.end("Hello again");
});
server.listen(8888);
Can you please tell me where you found response object? http.createServer return a callback function which have two arguments. They are response and request. response use for send data/information to client and request use for get data/information from client. So in your http.createServer callback function add response and request arguments. After that in callback function use response object. Like this.
var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {
"content-Type" : "text/html"
});
response.end("Hello again");
}).listen(8888);
var http = require("http");
var fs = require("fs");
http.createServer(function(request, response) {
console.log("User request received");
response.writeHead(200, {"Content-Type": "Text/plain"});
fs.createReadStream(process.argv[3]).pipe(response);
response.end();
}).listen(process.argv[2]);
console.log("Server is running...");
This program takes the port number and the file path as command line parameters.
When I run it in node, even though I pass the correct command line arguments, the file is not served when accessed from the browser
I don't know where the error is occurring
This might not be the best answer but it looks like the call to response.end() is closing the stream before the file is served. Following the logic on this answer:
createReadStream().pipe() Callback
You need a callback on when the stream closes, so I found this works but again, I don't know if this is the most elegant solution:
var http = require("http");
var fs = require("fs");
http.createServer(function(request, response) {
console.log("User request received");
response.writeHead(200, {"Content-Type": "Text/plain"});
var t = fs.createReadStream(process.argv[3]).pipe(response);
t.on('close', function(){
response.end();
});
}).listen(process.argv[2]);
I have the following Node.js code:
var http = require('http');
http.createServer(function(req, res)) {
console.log("URL request"+req.url);
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello World\n');
}).listen(9898, '127.0.0.1');
console.log('Server locally running at http://127.0.0.1:9898/');
I am using the Socket class in Java to make a socket that also connects to port 9898. I want whatever the Node.js writes (in this case 'Hello World'), to be processed by a Java class. So far, this is what I have for the Java class:
Socket s = new Socket(serverAddress, 9898);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
My question is how do I get the 'Hello World' to be read by the Java code, so that whenever I call System.out.println(input.readLine()), it prints 'Hello World'?
you had an extra ')' on the third line, but your code seems to otherwise work:
var http = require('http');
http.createServer(function(req, res) {
console.log("URL request"+req.url);
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello World\n');
}).listen(9898, '127.0.0.1');
console.log('Server locally running at http://127.0.0.1:9898/');
i guess you need to create some java functionality to make a http request to the url:port the node server is running on. it probably wont be as simple as 'input.readLine()'.
maybe something like this will help for getting the java code to get the data from node:
How can I get an http response body as a string in Java?
I try to put an html in a page in node.js and this is the code:
var http = require('http');
var fs=require('fs');
fs.readFile('C:\Users\Eventi\Desktop\Node.js\Progetti\ProveNodeJS\NodeJSProve\home.html', function (err, html) {
if (err) {
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});
When I go at the url http://localhost:8000 I obtain the error first argument must be a string or Buffer node js . Anyone can help me?
The reason is that your readFile() failed and err is set (html is probably undefined). You should fill in your if (err) {} block to do something useful when this is the case.
Also, the most likely reason for the error is that the backslashes are not escaped in your literal filename string. So instead you'll need:
'C:\\Users\\Eventi\\Desktop\\Node.js\\Progetti\\ProveNodeJS\\NodeJSProve\\home.html'
Escape your path:
fs.readFile('C:\\Users\\Eventi\\Desktop\\Node.js\\Progetti\\ProveNodeJS\\NodeJSProve\\home.html', function (err, html) {
And try again.
I wonder how can I send data from node.js to client?
example node.js code -
var http = require('http');
var data = "data to send to client";
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
}).listen(8125);
Now, I want to send the data variable to client and log it with JavaScript..
How can I do that?
Thanks ;)
EDIT: Does anyone know how to send array?
If You Want to do it after response.end you should use Socket.io or Server Send Events.
If you want it before res.end, you would make your code look like:
var http = require('http');
var data = "data to send to client";
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(data); // You Can Call Response.write Infinite Times BEFORE response.end
response.end("Hello World\n");
}).listen(8125);