I am new to Node Js. I am creating app with socket.io and express, which fetches tweets after user login. How can I create session so that tweets page should open only after login and not without login.
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, Twit = require('twit')
, io = require('socket.io').listen(server);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/login.html');
});
app.get('/tweets', function (req, res) {
res.sendfile(__dirname + '/twitter.html');
});
Configuring Express
var app = express();
app.configure(function () {
app.use(express.cookieParser());
app.use(express.session({secret: 'secret', key: 'express.sid'}));
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
server = http.createServer(app)
server.listen(3000);
Configuring Socket.IO
io = io.listen(server);
io.set('authorization', function (handshakeData, accept) {
if (handshakeData.headers.cookie) {
handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);
handshakeData.sessionID = connect.utils.parseSignedCookie(handshakeData.cookie['express.sid'], 'secret');
if (handshakeData.cookie['express.sid'] == handshakeData.sessionID) {
return accept('Cookie is invalid.', false);
}
} else {
return accept('No cookie transmitted.', false);
}
accept(null, true);
});
Reference
If you use Expressjs, look at the example from Expressjs repository, or read the article about cookie-based & store-based sessions.
Related
I defined a route in my Express app that supposed to execute a line of code then return a JSON file, but what happens is that the file is returned, but the line of code isn't executed.
This is the server code:
var express = require('express');
var body_parser = require("body-parser");
var path = require('path');
server = express();
server.use(body_parser.json());
server.use(body_parser.urlencoded({ extended: true }));
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
Inside index.html there is only a script tag defined like:
<body>
<script>
$(document).ready(function(){
$.getJSON("/request.json", function(data) {
console.log(data)
});
})
</script>
</body>
I can see the content of request.json file in chrome console, but the expected message "File "request.json" requested" isn't displayed on server's terminal.
Why the route isn't being executed?
The express.static is called before the /request.json route and already returns the file.
Use this:
const express = require('express');
const bodyParser = require("body-parser");
const path = require('path');
server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
You can write custom static middleware. Can write logic to not to serve file[exclude].
Note: Note recommend from me, better change route name of /response.json
var express = require("express");
var path = require("path");
var app = express();
var statics = express.static(path.join(__dirname, "/"));
function customServe(secure) {
return function (req, res, next) {
console.log(req.path);
if (req.path != "/response.json") return statics(req, res, next);
return next();
};
}
app.use(customServe());
app.get("/response.json", (req, res) => {
console.log("something...");
res.send({ json: "json" });
});
app.listen(8080, () => console.log("working on 8080"));
I have search a lot and I can't seem to start express js app. All I'm getting is 404 error.
Default app.js file which has http server and it works fine.
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(response);
});
server.listen();
And this is express js code which is not working. giving me 404 error.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
server.listen();
I also tried few other combination as well.
var express = require('express');
var app = express();
app.get('/', (req, res) => res.send('Hello World!'));
var http = require('http');
var server = http.createServer(app);
server.listen();
this one also didn't work
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => res.send('Hello World!'));
server.listen();
I also tried expressjs to create it own server and it also didn't work.
const express = require('express');
const app = express();
const port = 80;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
I also tried to remove port from app listen and not surprisingly it also didn't work.
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World!'));
app.listen();
I also tried everything from express-js-app-listen-vs-server-listen page but not successful.
This is the error I get
For others with the same A2 Hosting issue, the solution is actually so easy...
The problem with the application running the NodeJS deployment on cPanel. Phusion Passenger does not use the root path as '/', but as '/yourAppURL'. So in your NodeJS code, you have to add the specified AppURLPath to the call when using Express...
e.g.
//Instead of
app.get('/', (req, res) => res.send('Hello World!'));
//Change to
app.get('/YourSpesifiedAppURLPath/', (req, res) => res.send('Hello World!'));
Hi i have setup three project api(nodejs) , admin(angular 4) and website(angular 4) , after build i got two UI folder admin-dist and web-dist , I want to access these app based on URL '/admin' will access admin-dist and '/' will access web-dist , I have placed these two folder on of api folder
For accessing these app i have written node code like this ,But i am not able to access ,
Please help me, Thanks in advance ..
app.js
var express = require('express');
router = express.Router();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cookieParser = require('cookie-parser');
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')
var cors = require('cors');
var User = require('./models/user.model');
var dbConfig = require('./config/db');
var app = express();
app.use(cors());
app.use(cookieParser());
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, function (err) {
if (err) {
console.log('faild to connect with mongo DB', err);
}
else {
console.log('Connection open with mongo db');
}
})
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
var userRoute = require('./routes/user.route')(router);
// var profileRoute = require('./routes/profile.route')(app);
// var productRoute=require('./routes/products.route')(app);
app.use(express.static(__dirname + '/admin-dist'));
app.get('/admin', function (req, res) {
console.log('admin route');
return res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.get('/admin/*', function (req, res) {
res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.use(express.static(__dirname + '/front-dist'));
app.get('/', function (req, res) {
console.log('web route');
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.use('/*',function(req, res) {
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.listen(port, function (err) {
if (err) {
console.log(err);
}
else {
console.log('Server api runing on port ', port);
}
})
I want to initialize my socket inside a route and according to documents I have to pass server instance to my socket. I have a separate server.js file like this:
var app = require('./app');
var http = require('http');
var port = '2002';
app.set('port', port);
var server = http.createServer(app);
server.listen(port, function(err){
if(err)
console.log(err);
else
console.log('Server listening on port : ' + port);
});
module.exports = server;
and my router:
var express = require('express');
var server = require('../server');
var router = express.Router();
var io = require('socket.io')(server);
router.get('/', function(req, res, next){
res.render('index');
});
router.post('/', function(req, res, next){
io.on('connection', function(socket){
socket.emit('server emit', { hello: 'server emit' });
socket.on('client emit', function (data) {
console.log("Server received : " + data);
});
});
});
module.exports = router;
and my client script:
var socket = io('http://localhost:2002');
socket.on('connect', function() {
socket.on('server emit', function(data) {
console.log('inside eventtt');
console.log(data);
});
});
But I face this error in my browser console:
socket.io-1.4.5.js:1 GET http://localhost:2002/socket.io/?EIO=3&transport=polling&t=LPajDxI
I think the problem is due to wrong initialization of my socket on the server side, but I don't know how to handle the problem.
I am trying around with nodejs and socket.io
But my application refuses to work after a few requests. It takes a while and after some time it starts working again.
Here is the code for the nodejs-server, where i expect the issue.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('db.sqlite');
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
router.post('/', function (req, res) {
res.sendFile(__dirname + "/app/index.html");
});
router.get('/sample', function (req, res) {
res.sendFile(__dirname + "/app/sample.html");
});
router.post('/api/error', function (req, res) {
var data = req.body;
data.date = Date();
io.emit('error', JSON.stringify(data));
res.header("Access-Control-Allow-Origin", "*");
});
io.on('connection', function(socket){
console.log('a client connected');
});
app.use('', router);
app.use(express.static('app'));
app.use('/static', express.static('node_modules'));
// START THE SERVER
server.listen(port);
console.log('Magic happens on port ' + port);
The applikation is for monitoring errors in a full webstack.
The handler for POST /api/error isn't sending back a response, so the client will continue to wait. At some point, it may decide not to open any more connections to the server until the previous ones have been answered (or have timed out).
You can just send back a 200 response:
router.post('/api/error', function (req, res) {
var data = req.body;
data.date = Date();
io.emit('error', JSON.stringify(data));
res.header("Access-Control-Allow-Origin", "*").sendStatus(200);
});