Manipulating Cookies before serving - javascript

Scenario
I have a simple NodeJS server using the Express framework. I have some ReactJS pages that I need to serve. No Isomorphic for now.
Before serving, I want to check if the user has a particular cookie and then based on that I want to create a new cookie.
What I tried
Here is the code for my server.js file.
var express = require("express");
var app = express();
var Cookies = require("cookies");
app.use(function(req, res){
var cookies = new Cookies( req, res);
var userCookie = cookies.get("sso");
var isLoggedIn = cookies.get("isLoggedIn");
if(userCookie !== undefined && isLoggedIn === false){
cookies.set("isLoggedIn", true);
}
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});
So I am using express.static for serving static files from my build folder.
I tried moving the app.use(express.static(__dirname + '/build')); line above the previous app.use, but then the code never enters the cookies section.
I tried this simple thing. Even this didn't worked. I can see log hello, but the website isn't working.
var express = require("express");
var app = express();
app.use(function(req, res){
console.log("hello");
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});

There's a problem with your use of cookies. You're checking if isLoggedIn, the cookie value, === false, a boolean value. But cookies are always strings, so the comparison will always be false and you'll never set isLoggedIn to "true".
If your update your code to treat the values as strings it might work. Try something like this:
if(userCookie !== undefined && isLoggedIn !== "true"){
cookies.set("isLoggedIn", "true");
}

As jeremy's answer pointed out, I was using the cookies the wrong way. But that wasn't the core problem. If code would have run, express server would have thrown error. The real problem was that i wasn't calling the next middleware in the application’s request-response cycle. According to the docs
Middleware is a function with access to the request object (req), the
response object (res), and the next middleware in the application’s
request-response cycle, commonly denoted by a variable named next.
I wasn't calling the next.
So the updated running code is:
var express = require("express");
var app = express();
var Cookies = require("cookies");
app.use(function(req, res, next){
var cookies = new Cookies( req, res);
var userCookie = cookies.get("sso");
var isLoggedIn = cookies.get("isLoggedIn");
if(userCookie !== undefined && isLoggedIn !== "true"){
cookies.set("isLoggedIn", "true",{ httpOnly: false } );
}
next();
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8142;
app.listen(port, function() {
console.log("Listening on " + port);
});

Related

request.url showing two urls in node.js

I am getting two urls in req.url in http.creatServer() function.
If i console the current url it shows "/favicon.io" and "/test.txt".
I want to show the file "text.txt" content when user try to open the url "http://localhost:3000/test.txt".
Here is my code
var fs = require('fs');
var PORT = process.env.PORT || 3000;
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200, {'Content-type' : 'text/plain'});
console.log('----',req.url);
if(req.url === "/test.txt"){
fs.createReadStream(__dirname + "/test.txt").pipe(res);
}
else
{
res.end('Hello World!!');
}
}).listen(PORT);
console.log('Server Running at port ' + PORT);
Ohh..got your problem.
Node is Asynchronous event driven programming language.
so It wont wait unit the file content being read by request operation.
It will execute another request and your another request is favicon in pipeline.
so it will always return false. so that you will getting hello world every time.
use this and check
if('txt' == req.url.split('.')[1]){
var read = fs.readFileSync(__dirname + "/test.txt");
res.end(read.toString());
}

Node.js file server with file index

I have the below code for a file server and I would like to use and html page to show an index of the files that are available for download in the static folder "public1"
I currently can serve an html page if the user explicitly requests it but I can't make it automatically serve the html page. The commented out code is my attempt at serving the html page named "hello" by default. It doesn't work...
How can I make the html page display (by default) to the user that navigates to the ip address in a browser?
How can I make the html file show an index of files in the static folder?
So for this two part question, does anyone know how to do this? Can you point me in the right direction.
var express = require('express');
var server = express();
var port = 10001;
//server.get(__dirname + 'public1', function(req, res) {
// res.send('Hello.html');
//});
server.use(express.static(__dirname + '/public1'));
server.listen(port, function() {
console.log('server listening on port ' + port);
});
The easiest way to do this is by using the serve-index and serve-static middleware that is available for express. The below example code works, just swap out the process.cwd() for whatever directory you'd like to serve.
const express = require('express');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
const path = require('path');
const server = express();
const port = process.env.PORT || 3000;
function setHeaders(res, filepath) {
res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath));
}
const dirToServe = process.cwd();
server.use('/', serveIndex(dirToServe, {icons: true}));
server.use('/', serveStatic(dirToServe, {setHeaders: setHeaders}));
server.listen(port, () => {
console.log('listening on port ' + port);
});

req.get('host') - expressJS - same value on different hosts -?

hi I try to get host name in node express js -
i use:
var express = require('express'),
app = express();
var port = process.env.PORT || 3000;
app.use(function(req,res,next){
if (req.hostname == "domain1") {
app.get('/', function(req,res){
res.send('Domain1 is active');
}) else if (req.hostname == "domain2") {
app.get('/', function(req,res){
res.send('Doamin2 is active');
});
}
}
next();
});
app.listen(port);
but its works correct only on the first host - if i change host - I have first result
any advice ?

Node JS Express all requests showing 404

All requests are showing GET / 404 8.128 ms-13 in console.
I have posted the code below, there is no error in the code. I can run other NodeJS applications. But this is showing 404 in console. It is not even showing the fav icon. It worked once showing Cannot GET / error and the fav icon was visible at that time.
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var logger = require('morgan');
var port = process.env.PORT || 8001;
var four0four = require('./utils/404')();
var environment = process.env.NODE_ENV;
app.use(favicon(__dirname + '/favicon.ico'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use('/api', require('./routes'));
console.log('About to crank up node');
console.log('PORT=' + port);
console.log('NODE_ENV=' + environment);
switch (environment){
default:
console.log('** DEV **');
app.use(express.static('./src/client/'));
app.use(express.static('./'));
app.use(express.static('./tmp'));
app.use('/app/*', function(req, res, next) {
four0four.send404(req, res);
});
app.use('/*', express.static('./src/client/index.html'));
break;
}
app.listen(port, function() {
console.log('Express server listening on port ' + port);
console.log('env = ' + app.get('env') +
'\n__dirname = ' + __dirname +
'\nprocess.cwd = ' + process.cwd());
});
According to http://expressjs.com/starter/static-files.html I think that your route here app.use('/*', express.static('./src/client/index.html')); will use ./src/client/index.html as the base path and append whatever you provide to find a file. For example
/some-file will look for ./src/client/index.html/some-file which is obviously not existed
In case you want to understand it more, the static middleware use https://github.com/pillarjs/send internally to stream file
So you can do this
app.use('/*', express.static('./src/client'));
It will, by default, set / to src/client/index.html, you can change that behaviour by setting index option as specified here https://github.com/expressjs/serve-static
If you want to redirect /* to ./src/client/index.html do this
// first set the static middleware
app.use('/public', express.static('./src/client'));
// then use redirect
app.get('/*', function(req, res, next){
res.redirect('/public/index.html');
});
This setup will redirect everything to public/index.html. If you want to add APIs or other routes, put it before the app.get('/*')

combining functionality of two Node servers with different initial set up

I have two node servers and I need to combine them so one server has the functionality of both. They were set up a little differently and I'm not sure how to resolve it.
The first server has the require statements at the top, routes in the middle and creates the server at the bottom like this:
var express = require('express');
var routes = require('./routes');
etc..
// middleware
// routes
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The second one looks like this:
var express = require('express')
, app = express()
, server = app.listen(80)
, io = require('socket.io').listen(server)
, fs = require('fs')
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
io.sockets.on('connection', function (socket) {
});
I cut pasted part of it so now the first server script looks (roughly) like this.
// All imports
var express = require('express');
var routes = require('./routes');
var mongoose = require('mongoose');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');
var multer = require('multer');
var connect = require('connect');
var methodOverride = require('method-override');
var io = require('socket.io');
// middleware
// routes
// trying to make this a route
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Combining the two scripts has resulted in an error listed below at the line listed below.
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot call method 'on' of undefined:
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
I don't understand why I'm getting this error after changing the two require statements and moving the server creation and listening to the bottom of the server. Does anyone know how I can fix this?
You're requiring socket.io, which has a .listen method, not an .on method. Once you call .listen, you'll get back an object that has the .on method you're trying to use.
io = require('socket.io').listen(server);
(You're also missing server, which is created in the second script by calling express().listen(somePortNumberLike80)
You can't just copy and paste code and expect it to work, really.

Categories

Resources