I'm using node version 0.10.3 and Express 3.1.1.
I'm trying to return a simple response, but I'm getting the following error:
http.js:692
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:692:11)
I've read a lot about it, and tried many solutions but I'm still getting that error.
I've used node-inspector and i'm getting the error after that line -
res.render('index', { title: 'Express' });
app.js:
/**
* Module dependencies.
*/
var express = require('express')
, http = require('http')
, path = require('path')
, socketio = require('socket.io');
var app = express()
, server = http.createServer(app)
, io = socketio.listen(server);
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'hjs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
io.configure('production', function(){
io.enable('browser client etag');
io.set('log level', 1);
});
io.configure('development', function(){
io.set('log level', 1);
});
io.sockets.on('connection', function(socket) {
socket.on('event', function(event) {
socket.join(event);
});
});
require('./routes')(app, io);
routes/index.js:
var utils = require('../utils')
, config = require('../config')
, io;
module.exports = function(app, socketio) {
io = socketio;
app.get('/', index);
};
var index = function(req, res){
res.render('index', { title: 'Express' });
};
views/index.hjs:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>{{ title }}</h1>
<p>Welcome to {{ title }}</p>
</body>
</html>
package.json:
{
"name": "blabla",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "app.js"
},
"dependencies": {
"express": "3.0.3",
"hjs": "0.0.4",
"cradle": "0.6.4",
"twiliosig": "0.0.1",
"socket.io": "0.9.11"
},
"subdomain": "blabla",
"engines": {
"node": "0.6.x"
}
}
Any Clue?
Seems to be an error with your version of socket.io.
Use this:
"dependencies": {
"express": "3.0.x",
"hjs": "0.0.4",
"cradle": "0.6.4",
"twiliosig": "0.0.1",
"socket.io": "0.9.x"
}
Tested with socket.io#0.9.16
Related
I am creating a simple socket io application. I followed all tutorials online to implement socket-io via Node JS. The current code worked only once and after connecting to the socket it got disconnected automatically. Since then I tried all PnC but it has not connected server side.
Can anyone please help me identify what stupidity I have done? Also I do not understand that whether it is client side problem or library problem.
package.json
{
"name": "IntellicarMaps",
"version": "1.0.0",
"description": "Demo app showing the use of Google Maps for Intellicar",
"main": "server.js",
"author": "Prateek",
"dependencies" : {
"express" : "~4.7.2",
"mongoose" : "~4.1.0",
"morgan" : "~1.2.2",
"body-parser": "~1.5.2",
"jsonwebtoken": "^5.0.2",
"method-override": "~2.1.2",
"socket.io": "~1.4.8"
}
}
server.js
// Dependencies
// -----------------------------------------------------
var express = require('express');
var mongoose = require('mongoose');
var port = process.env.PORT || 3000;
var database = require('./app/config');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
var server = require('http').createServer(app);
global.io = require('socket.io').listen(server);
//------------------
// Express Configuration
// -----------------------------------------------------
// Sets the connection to MongoDB
mongoose.connect(database.localtest.url);
// Logging and Parsing
app.use(express.static(__dirname + '/public')); // sets the static files location to public
app.use('/bower_components', express.static(__dirname + '/bower_components')); // Use BowerComponents
app.use(morgan('dev')); // log with Morgan
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.urlencoded({extended: true})); // parse application/x-www-form-urlencoded
app.use(bodyParser.text()); // allows bodyParser to look at raw text
app.use(bodyParser.json({ type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride());
//----------
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// Routes
// ------------------------------------------------------
require('./app/routes.js')(app);
// Listen
// -------------------------------------------------------
//app.listen(port);
server.listen(port);
console.log('App listening on port ' + port);
//------------------------
// Socket io connection
//------------------------
io.on('connection', function(socket){
console.log('a user connected'); //this is not printing in console.
socket.emit('my other event', { my: 'data' });
//socket.on('disconnect', function(){
//console.log('user disconnected');
//});
});
io.emit('message',{"AlarmName":"CPU_FAN_DOWN"});
addForm.html(Client)
<script src="../lib/socket.io.js"></script>
<script>
var socket = io('http://localhost', {'force new connection': true});
socket.on('message', function (data) {
console.log(data);
});
</script>
socket.io.js in lib folder
this file is always loaded,i have checked in browser console
I'm having issues deploying my app on Heroku. I keep getting a screen in my browser saying Application Error. From what i've read this is something with MongoLab.
I have set my PROCESS.ENV.MONGOLAB_URI correctly on heroku and I can't get it to work. I have also tried adding a new user to MongoLAB for this DB and even that user won't work as well.
I am Process.env.PORT because I am using Socket.io. Is it something in my app.js?
var express = require('express');
var http = require('http')
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://localhost/queueThat');
var db = mongoose.connection;
var routes = require('./routes/index');
var app = express();
var server = http.createServer(app);
//Stuff for Sockets
var io = require('socket.io').listen(server);
//sockets
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
//Connect to the Socket
io.on('connection', function(socket){
socket.on('song send', function(song){
io.emit('song send', song)
console.log('artist on')
})
socket.on('artist send', function(artist){
console.log('artist on')
io.emit('artist send', artist)
})
//Disconnect
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
var port = (process.env.PORT || 8000);
server.listen(port, function() {
console.log("Listening on " + port);
});
module.exports = app;
I have also tried adding my node and NPM versions to no avail. Any ideas? Package.json looks like this.
{
"name": "queueThat",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.13.2",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"ejs": "^2.3.4",
"express": "~4.13.1",
"mongoose": "*",
"morgan": "~1.6.1",
"serve-favicon": "~2.3.0",
"socket.io": "*"
},
"engines": {
"node": "5.4.0",
"npm": "3.3.12"
}
}
Application Error doesn't mean that there is something wrong with MongoLAB, not necessarily.
To be clear you need to double check few places:
You need to have proper Procfile in the root folder of your project
Be aware of postinstall npm script.
Also you could check your logs on heroku heroku logs -n 200 (200 or more lines if needed) to be sure what's the problem you have.
I am facing an issue rendering the 'EJS' Express template while running the node.js server. I have provided the codes below. As you can see, I am implementing the http.createServer(function (req, res) to read and write messages to the client. But the template holding the HTML code doesn't get rendered. The main objective of the code is for the client to post a message 'Hello from Client' to the server and the server responding to the client with 'Hello from Server'.
app.js (Server Side)
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, request = require ('request')
, cheerio = require ('cheerio')
, $;
var app = express();
//console.log($('[class = "orange"]').attr('id'));
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(function (req, res) {
var body="";
console.log('Request received: ');
req.on('data', function (chunk) {
body +=chunk;
});
req.on('end', function(){
console.log("Body: "+body);
res.write('Hello from Server');
res.end();
});
}).listen(3000);
index.ejs (Client Side)
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<input type="button" id="stopButton" value="Button1"/>
<input type="button" id="stopButton2" value="Button2"/>
<p>Welcome to <%= title %></p>
<ul id="fruits">
<li id= "1" class="apple">Apple</li>
<li id = "2" class="orange">Orange</li>
<li id = "3" class="pear">Pear</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
var formData = {data: "Hello from Client"};
$.ajax({
url: 'http://localhost:3000',
dataType: "json",
type: 'POST',
data: formData,
jsonpCallback: 'callback',
success: function (data, textStatus, jqXHR) {
var ret = jQuery.parseJSON(data);
console.log(ret.msg);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Error received");
}
});
});
</script>
</body>
</html>
package.JSON
{
"name": "NewProject",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.2.6",
"ejs": "*"
}
}
Earlier I had tried using app.get which had worked.
What is the primary difference between using app.get(), request() and http.createServer(). When should we use what?
It's not gonna work that way. Have a loo at the docs:
http://expressjs.com/starter/hello-world.html
For example:
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post('/hello', function (req, res) {
res.send("Hello from server");
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Also, please use a recent version of Express, yours is outdated.
This app works fine locally and works on openshift with no errors, however the views aren't rendering it is just printing the source code. I tried deleting and recreating the app but still no luck.
Here is part of my server.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require("fs");
var handlebars = require("handlebars");
var WebPageTest = require('webpagetest');
// Web Page Test - API key.
var wpt = new WebPageTest('www.webpagetest.org', '1234567890');
var router = express.Router();
app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/img", express.static(__dirname + '/img'));
/***** Views *****/
// Homepage.
app.get('/', function(req, res) {
var template = fs.readFileSync("views/index.html", "utf8");
// handlebars data, optional.
var source = {
message : "Homepage!"
};
var pageBuilder = handlebars.compile(template);
var pageText = pageBuilder(source);
res.writeHead(200, {"Context-Type": "text/html"});
res.write(pageText);
res.end();
});
/***** Start App *****/
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 5000;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
app.listen(server_port, server_ip_address, function(){
console.log("Listening on " + server_ip_address + ", server_port " + server_port);
});
Here is part of the package.json
{
"name": "wpt",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"body-parser": "^1.10.0",
"express": "^4.10.6",
"webpagetest": "^0.3.1",
"mongoose": "^3.8.21",
"handlebars": "^2.0.0",
"express3-handlebars": "^0.5.2",
"fs":"*"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
I added fs to the dependencies manually but it didn't seem to have any effect.
It's probably a lot easier to just use a handlebars Express views engine such as hbs. Example:
// ...
var hbs = require('hbs');
app.engine('hbs', hbs.__express);
app.engine('html', hbs.__express);
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
hbs.localsAsTemplateData(app);
app.get('/', function(req, res) {
res.render('index.html', {
message: 'Homepage!'
});
});
// ...
I am using dustjs as the templating engine in an express app, and was wondering if anyone has successfully used the contextDump helper in a server side template in express? I followed the consolidate example for integrating dust with express, and it is working well. The helpers are there, as I'm able to do a simple test with the eq helper and it works. but when trying to dump the context I'm not seeing it anywhere. here is a sample template:
{>layout/}
{<content}
<ul>
{#users}
<li>{username} - Create New Task
<ul>
{#user.tasks}
<li>{title} - Delete Task |
Update Task</li>
{/user.tasks}
</ul>
</li>
{/users}
</ul>
{/content}
{#contextDump to="console"/}
Here's my app.js:
var express = require('express');
var app = express();
var http = require('http');
var path = require('path');
var db = require ('./models');
var dust = require('dustjs-linkedin');
var cons = require('consolidate');
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('models', db);
//configure dust
app.set('view engine', 'dust');
app.set('template_engine', 'dust');
app.engine('dust', cons.dust);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//require routes
require('./routes')(app);
require('./routes/user')(app);
require('./routes/task')(app);
db
.sequelize
.sync({ force: true })
.complete(function (err) {
if (err) {
throw err;
} else {
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
}
});
and here's package.json:
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.6",
"sequelize": "~2.0.0-beta.5",
"mysql": "~2.0.0-rc2",
"lodash": "~2.4.1",
"async": "~0.2.9",
"dustjs-linkedin": "~2.2.2",
"dustjs-helpers": "~1.1.1",
"consolidate": "~0.10.0"
}
}
Thanks!