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);
Related
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
I'm currently teaching myself more about server code, specifically using Node.js and Express, and I'm having a lot of trouble with receiving and parsing a JSON object sent from a POST request. I have looked at numerous other posts (linked to below) and I can't figure out for the life of me what's going wrong. Here's what I've looked at:
Javascript: Send JSON Object with AJAX
Javascript : Send JSON Object with Ajax?
How do I consume the JSON POST data in an Express application
How do I consume the JSON POST data in an Express application
Send POST data using XMLHttpRequest
Send POST data using XMLHttpRequest
How do you extract POST data in Node.js?
How do you extract POST data in Node.js?
All of these are putting me on the right track, but I'm not quite there and thus looking for help. Here's the code I'm working with:
Send POST Request
var button = document.querySelector("#button");
button.onclick = function(){
console.log("Getting data from local server");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/data/test.json", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(JSON.stringify({"latitude": 41.2418, "longitude": -70.8898}));
};
Handle POST Request In Server
var http = require("http");
var fs = require("fs");
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");
var port = process.env.PORT || 3000;
//tells express where to find all the static files (HTML, CSS, etc) and load them into the browser
app.use(express.static(path.join(__dirname, '../client')));
//tells the application to use body-parser as middleware so it can handle post requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//routing methods
//deal with incoming GET and POST requests to the server
app.get("/", function(req, res){
res.send("Submitted GET Request");
})
//only handles incoming POST requests to the test.json resource
app.post("/data/test.json", function(req, res){
console.info("Submitting POST Request to Server");
console.info("Request body: " + req.body);
//write the file
fs.writeFile(__dirname + "/../client/data/test.json", req.body,
function(err){
if(err){
console.error(err); //print out the error in case there is one
return res.status(500).json(err);
}
//resolve the request with the client
console.info("updated test.json");
res.send();
});
})
//tell the express object to create the server and listen on the port
app.listen(port);
console.log("Listening on localhost:" + port);
Whenever I try to print out the contents of "req.body" I get the output of "[object Object]". Any ideas?
EDIT:
My issue has been solved. I have changed
console.info("Request body: " + req.body);
To
console.info("Request body: " + JSON.stringify(req.body));
I also changed my Content-Type in my POST XMLHTTPRequest to "application/json" to help with formatting.
"[object Object]" is the default result of JavaScript's implicit toString operation, which it uses when trying to write a string representation of that object to the file.
Try writing JSON.stringify(req.data) to the file instead.
Also, on the client side – consider changing your Content-Type header to match:
xhr.setRequestHeader("Content-Type", "application/json");
If your post body is expected to be JSON, then change this line
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
To
xhr.setRequestHeader("Content-Type", "application/json");
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'm following this beginner node.js tutorial (http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef7-0f7ecbdd56cb) and i have just created my first server using this code:
var http = require("http")
http.createServer(
function(request, response){
response.writeHead(200, {"Content-Type":"text/plain"})
response.write("hello world")
response.end
}
).listen(3333)
This works great, but when i go to the url localhost:3333/ i see the words "hello world" very briefly and then it just dissapears.
See this vine for a quick video: https://vine.co/v/MBJrpBEQvLX
Any ideas?
Put your Hello World in the response#end(). I'd also suggest that your read the NodeJS API
http.createServer(function (req, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(3333);
You forgot to put parentheses at the end of response.end().
The code should read:
var http = require("http");
http.createServer( function(request, response){
response.writeHead(200, {"Content-Type":"text/plain"});
response.write("hello world");
response.end();
}).listen(3333);