Here is my code:
var express = require('express'),
app = express.createServer(express.logger());
app.use(express.bodyParser());
app.get('/', function(request, response) {
var name = request.param('name', null);
response.header('Content-Type', 'text/event-stream');
var t = setInterval(function(){
response.write('Hello World by '+name+' (using http-1.1 streaming data!)<br />');
}, 2000);
/*request.socket.on('close', function() {
clearInterval(t);
}); */
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
//clearInterval(t);
console.log("Listening on " + port);
});
I am using express because I am testing this in heroku and I used the guide there.
So when I open the app I get a download popup with the data in the file (downloaded) instead of the html (dom) response.
What did I do wrong? (is it a browser problem?)
Edit:
#Joe, has solved my initial problem but yet, I have two questions:
1) Why i don't need to insert a 'correct' content type? (of streaming?)
2) Why does this code out put only after along time (about half a minute).?
If you are trying to display it as HTML you will want your Content-Type to be text/html
Related
I trying to find my way into node.js transfering a local sports statistics application written in c#.
Writing the http server, i observe that every time i refresh (after the first time) the server to make a new request, i have 2 response.
I strip the code to eliminate every other possible cause and the "problem" still exists.
Code
var http = require("http");
var counter = 0;
var port = process.env.PORT || 3000;
var requestListener = function (req, res) {
counter += 1;
res.end("Hits: "+ counter);
};
var server = http.createServer(requestListener);
server.listen(port, function (err) {
console.log("server listen on port " + port);
});
Is this the normal behaviour or i missing something?
In a browser page, this is often caused by the browser requesting your page and then requesting some other resource from the same host (such as the favicon for the page). You can see exactly what is being requested to shine some light on what's happening by logging req.url:
var http = require("http");
var counter = 0;
var port = process.env.PORT || 3000;
var requestListener = function (req, res) {
// add logging for what url is being requested
console.log(req.url);
counter += 1;
res.end("Hits: "+ counter);
};
var server = http.createServer(requestListener);
server.listen(port, function (err) {
console.log("server listen on port " + port);
});
Is this the normal behaviour or i missing something?
This is normal and expected. If the extra request turns out to be a favicon request, then you can disable that as explained here: How to prevent favicon.ico requests?
Note: it is a bit unusual to have a web server that does not even look at the requesting URL and does the same thing no matter what path request was sent to it. If you were looking at the URL and branching your code based on the URL, you would likely be avoiding requests that you were not expecting.
i am having an xml file.I need to expose an api in such a way that it can consume xml files throughnodjs server api.
how can i receive a simple xml file in my nodejs server. i need a nodejs server script.
Try this code after struggling sometime I successfully get the code as per your need.
var express = require('express');
var fs=require('fs');
var app = express();
var conf;
var result;
app.get('/Excel', function(req, res){
result=fs.readFileSync('E:/User/nodejs/nodejs/tasks/result.xml');
res.end(result);
});
app.post('/posting',function(req,res){
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function (){
fs.writeFile('E:/User/nodejs/nodejs/tasks/result.xml', body, function() {
console.log(body);
res.end('Successfully Posted');
});
});
});
app.listen(3000);
console.log('Listening on port 3000');
After you run the server Post the data in content-type as application/xml using http://localhost:3000/posting and place your code in body and as result result.xml file will be created with the data.And you can get this file by http://localhost:3000/Excel.Hope this helps for you.
You can use a simple XML parser middleware such as express-xml-bodyparser. A working examples with express can be found in the above mentioned site.
The thing I want to do is modify the response body.
For this I am using a middleware that gets called at every request.
To achieve it, I took a demo application from github https://github.com/ccoenraets/nodecellar . I added a middleware in the server.js similar to the example given on express logging response body.
Still I am unable to modify the response body, as res.send = function (string) does not get called.
Below mentioned is the code. Please let me know what wrong am I doing here.
var express = require('express'),
path = require('path'),
http = require('http'),
wine = require('./routes/wines');
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 4000);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser()),
app.use(express.static(path.join(__dirname, 'public')));
app.use(logResponseBody);
});
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.post('/wines', wine.addWine);
app.put('/wines/:id', wine.updateWine);
app.delete('/wines/:id', wine.deleteWine);
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
function logResponseBody(req,res,next){
var send = res.send;
console.log("send resp is: "+send);
res.send = function (string) {
var body = string instanceof Buffer ? string.toString() : string;
console.log("Body found is: "+body);
body = body.replace(/<\/head>/, function (w) {
return 'Modified head' + w;
});
send.call(this, body);
};
res.on('finish', function(){
console.log("Finished " + res.headersSent); // for example
console.log("Finished " + res.statusCode); // for example
})
next();
}
PS: I am starting a new thread for a similar question as I have less than 50 reputation.Therefore cant add comments there.
The best way to add middleware to an express app is to use the app.use method, so you can remove the whole http.createServer block and replace it for something like
app.use(function(req, res, next) {
//do everything you want to happen on every request
next();
});
app.listen(app.get('port'), function() {
console.log('listening on port ' + app.get('port'));
});
For more info on app.use, check the express app use documentation.
js and am trying to create a web server and server side code for my web application.
I understand express is used to get access to all static files.
I am trying to start a simple server using express as follows:
var express = require("express");
var url = require("url");
var http = require("http");
var port = 3000;
var app = express();
app.use(express.static(__dirname + "/Client"));
http.createServer(app).listen(port, function(req,res){
console.log("Server running at: " + "http://" + port);
res.writeHead(200,{
"Content-Type":"text/plain"
});
});
I cant seem to do anything with my res variable in my callback, which I am trying to use as a response object. Allowing me to do things like:
res.end(¨hello world¨);
Is this callback even allowed, or how can I start sending responses etc. I am on virtual box (linux) machine, and using res always gives error (undefined methods etc.). Thanks in advance,
http.createServer(app).listen(port, [hostname], [backlog], [callback])
There are no parameters given to the callback function. This is why req and res are undefined.
So you may change your code to:
app.listen(port, function(){
console.log("Server running at: " + "http://localhost:" + port);
});
app.get('/', function(req,res) {
res.status(200).send('Hello World!')
})
So take a look at the documentation of app.listen() and app.get()
I am not able to run socket.io code in node.js, console.log() is also not displaying when running the code. Below is the code.
app.js
var express = require('express');
var http = require('http');
var app = express();
app.set('port', process.env.PORT || 3000);
app.post('/testStream',test.testStream);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
module.exports.appServer = server;
and I have created a test.js file where I am accessing this exported variable appServer.
var server = require('../app.js');
exports.testStream = function(req,res){
var io = require('socket.io').listen(server.appServer);
io.on('connection',function(socket){
console.log("in socket");
fs.readFile('E:/temp/testimg.png',function(err,buf){
socket.emit('image',{image: true,buffer: buf});
console.log("test image");
});
})
}
when the code runs it stucks and not showing the console.logs(). What I am doing wrong over here. Any help is very much appreciated.
I would suggest following the code structure as suggested in socket.io docs.
Also, you should not be calling io.listen or io.on('connection') inside your testStream express middleware. These are things you should only be doing once, and ideally they should happen during startup, inside app.js and not in reaction to a POST request. In fact, I'm not sure what the purpose of your testStream middleware is, its not even returning any response (eg res.end())
If you want to handle socket connections in a separate module you can, but instead of exporting your app's server the way you are, try passing the io instance as variable to your submodule. In short, try this:
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var test = require('./test')(io);
app.set('port', process.env.PORT || 3000);
server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
test.js
module.exports = function(io) {
io.on('connection', function(socket) {
console.log("in socket");
fs.readFile('E:/temp/testimg.png', function(err, buf) {
socket.emit('image', {
image: true,
buffer: buf
});
console.log("test image");
});
});
};