FAQ Database Discussion Community


Get local json file using request-promise

javascript,json,angularjs,node.js,express
I'm making a node/express app and am querying a test json file using npm request-promise. Node is spitting out the following error in my <title> tags: Error: <title>Invalid URI "../testJSON/user.json"</title> I believe my pathing is correct, so am unsure why it's an invalid URI. I've also provided the entire project...

What is the bin folder in an express application for?

express
When creating an express application express <App-name> it creates a few folders and files including a bin. What is the bin folder used for exactly?...

Passing a var from server to client

javascript,node.js,express,ejs
I'm using node.js + Express + EJS. In my route, I'm accessing an external API to get some data: router.get('/', function(req, res, next) { var request = https.get(url + 'products.json', function(response){ var buffer = "", route; response.on("data", function (chunk) { buffer += chunk; }); response.on("end", function (err) { // finished...

error while using node proxy

javascript,node.js,express,node-http-proxy
Im using the following program and when I run it i got following error I was able to run the app but when i put in the browser localhost:3000 I got this error in the console... **Error: connect ECONNREFUSED** at exports._errnoException (util.js:746:11) at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1000:19) This is the...

Passing data from server/app.js to controller Angular-fullstack + multer

javascript,angularjs,node.js,express,multer
I'm struggling to get a filename passed from server/app.js to a controller in client/app/ I am using Multer to deal with the file upload which is working fine but i need to pass the filename back to the client to display it in the next view. Here is the code...

Send a POST when the user hits the bottom?

node.js,mongodb,express
There are loads of questions that have this same problem, but all the ones I've found will only tell you how the actual javascript works, not the routing for this kind of thing. So I'm a bit lost at the moment trying to implement the html and routing side of...

how to properly send and receive form data in an angular/node application

angularjs,node.js,express,mean-stack,meanjs
I'm writing an app based on mean.js boiler plate I have a form in my angular view, which need to send some formData: <form name="form" ng-submit="postUpdate()"> <div class="form-group"> <fieldset> <legend><strong>Salesforce Opportunity</strong> </legend> <div class="col-sm-6"> <label for="opportunityId">Opportunity ID</label> <input id="kw" name="opportunityId" type="text" placeholder="kw" class="form-control" ng-model="kwRequired"/> ...... In my angular controller, I...

Using react-router and express with authentication via Passport.js - possible?

javascript,node.js,express,reactjs,passport.js
So I'm working on a project that incorporates React, Express.js+Passport and Webpack. I understand the concept of pushing everything to a 'master' React component via react-router, then letting it hash out what gets displayed for the given route. That would work great here, I think. To be upfront, I am...

Nodejs express catch a call to a public file on the server

node.js,express
I'm building a site in node.js express and Angularjs. The whole site is static and I serve it through public like so: app.use(express.static(path.join(__dirname, 'public'),{})); How can I catch in express a call to a specific page? I tried this: app.all("/app",multipart,function(req, res, next){ console.log("Checking if the user is logged"); }); The...

How to create a MySQL schema when deploying with Heroku (Express Server)

mysql,heroku,express,cleardb
Suppose I have the following server.js file: server.js var express = require('express'); var app = express(); var mysql = require('mysql'); var dbhelpers = require('./public/database_helpers.js') var bodyParser = require('body-parser') app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/public/views')); app.use(express.static(__dirname + '/public/controlers')); app.use(express.static(__dirname + '/public/lib')); app.use(bodyParser()) var connection = mysql.createConnection({ **Correct info** });...

NodeJs + ExpressJs app routing odd behavior

angularjs,node.js,express,mongoose,passport.js
I am learning ExpressJS. So far I have setup a simple todo app with user authentication using PassportJS. I use Mongoose for repository. There is nothing in the web to explain the odd behavior that I'm seeing with my route setup. Scenario: When I hit get /passport it will direct...

Not able to access result returned from mongoDb outside query

node.js,mongodb,express
I am working with node.js using express and mongoDb. I am trying to retrieve data from database "local" and collection "borrower" and pushing it into an empty array collectionOne. It is rendering this array on the view page. I want to use _id pushed in an array b_ids from this...

Express.js server with Apache Tomcat

node.js,tomcat,express
I am making a sample web application in node.js using express.js. I am getting a little confused when using apache-tomcat as my web server. I have two doubts: When i run apache-tomcat as a web server and my express.js server is providing me services at port number 4000, how does...

Need to send response after forEach is done

node.js,mongodb,express,mongoose
I'm working with NodeJS + Mongoose and I'm trying to populate an array of objects and then send it to the client, but I can't do it, response is always empty because it is sent before forEach ends. router.get('/', isAuthenticated, function(req, res) { Order.find({ seller: req.session.passport.user }, function(err, orders) {...

How to validate presence of parameter in API call

javascript,node.js,express
I've setup middleware to check for the presence of a required parameter in an API call. The problem is, if the parameter is missing my middleware never gets called. I simply get a generic 404 error because the route couldn't be identified. I'm trying to figure out what I'm missing:...

Set multer properties inside an express route

node.js,express,multer
Instead of attaching multer to the entire express app, i am trying to include it just for specific routes, which is better since you will be preventing uploads to every route handling post. Problem is, i am unable to set it properties inside a route. var router = require('express').Router(), multer...

Accesing handlebars variable via javascript

javascript,node.js,express,handlebars.js
I'm generating a handlebars view for express js framework, and I need to access the variables I pass to the view from inside a separate JavaScript file. For example: var foo = {{user.name}} Someone got an idea ? Helper ? Thanks per advance ! PokeRwOw...

Angularjs Login authentication redirection getting — Error: Can't set headers after they are sent

javascript,angularjs,node.js,express
Very new to NodeJS/AngularJS. I am having problem getting a login page to redirect to another page once the id and password are verified. Codes in the controller are as follows triggered by the route '/login/check': exports.logincheck = function(req, res) { User.findOne({email: req.body.email}).exec(function (err,user) { if (!user) { err =...

unable to add property to the json object

node.js,express,mongoose
I am trying to add status to a response on successful update but I am not able to add the status property to json object of form. Here is my code apiRouter.post('/forms/update', function(req, res){ if(req.body.id !== 'undefined' && req.body.id){ var condition = {'_id':req.body.id}; Form.findOneAndUpdate(condition, req.body, {upsert:true}, function(err, form){ if (err)...

Is express similar to grunt? what is the difference? what are the advantages of express over grunt?

node.js,express,gruntjs,mean-stack
I've been working on node,grunt,bower and yeoman from couple of months. I came across MEAN stack applications, in which expressjs is providing the server environment(my understanding). Are both grunt and express similar? Requesting for some helpful link on express and MEAN stack. ...

Express can't set headers after they're sent while downloading from mobile

node.js,express,download
I have fairly simple route defined: router.get('/download', function(req, res){ var file = __dirname + 'file.ext'; res.download(file); }); It works fine when I'm making requests from my comp, but once I do it from smartphone, server crashes and I get following error: throw new Error('Can\'t set headers after they are sent.');...

Socket.io client does not connect to server

node.js,express,socket.io
I am trying to make a Node.js app that will have an embedded chat. I am using socket.io to create that chat. I have attempted to set up my server / client, but the client does not seem to be connecting. I have my application to set log when sockets...

How would you test this route code?

javascript,node.js,unit-testing,express,sequelize.js
I have the following route code. User is a sequelize model, jwt is for creating a JWT token. I want to avoid hitting the db, so I want to stub out both dependencies. User.create returns a Promise. I want to be able to assert that res.json is actually being called....

sending multiple files down the pipe

node.js,express
we're using express 4 and right now I have something like this: var express = require('express'), router = express.Router(); router.get('/local_modules/*', function (req, res, next) { var moduleName = req.url.match(/local_modules\/(.*?)\//).pop(1) res.sendFile(filePath + '.js'); } and I wanna do something more like: router.get('/local_modules/*', function (req, res, next) { var moduleDir = req.url.match(/local_modules\/(.*?)\//).pop(1)...

Why is address undefined in my app?

node.js,express,jasmine,supertest
I have a simple express app: var express = require('express'); var path = require('path'); var app = express(); exports.app = app; var index = require('./routes/index'); app.use(express.static(path.join(__dirname,'client/dist/'))); app.get('/', index.get); function start(){ var port = process.env.PORT || 8080; app.listen(port, function(){ console.log('app is running on port: ' + port); }); }; exports.start =...

Write NodeJS stream into a string synchronously

node.js,express
I know that one can synchronously read a file in NodeJS like this: var fs = require('fs'); var content = fs.readFileSync('myfilename'); console.log(content); I am instead interested in being able to read the contents from a stream into a string synchronously. Thoughts?...

Send code via post message is not working

javascript,node.js,express,postman
I wanted to send code to some node application and I use the postman with post message and in the body I put the following: module.exports = function() { var express = require('express'), app = express(); app.set('port', process.env.PORT || 3000); return app; } in the header of the request I...

Is there a way to fire an event every time an ajax call in made in AngularJS?

javascript,ajax,angularjs,express
What I'm trying to do is every time a call to the backend is made, I want a spinner to load up with a dark overlay. I know I can do this by simply running the spinner before the call is made, but I'm working with multiple developers and I...

Full stack javascript routing explanation needed

javascript,node.js,express
I've scaffolded a full stack Mongo, Express, Angular, Node app using yeoman with the Angular Fullstack generator It has created a server/app.js file, which executes a routes.js to handle resources being served by the express server. The meat of routes.js looks like this: // Insert routes below app.use('/api/things', require('./api/thing')); app.use('/api/users',...

How to correctly use Express 4 multiple routers

javascript,node.js,express,routes
I'm attempting to use the Express 4 Router to use a different router based on the path. I want all /api/v2/ routes handled by version2, and every other route handled by version1. The below setup serves me all the version1 routes correctly, but seems to ignore version2 as I get...

Csurf invalid csrf token Express / nodejs

node.js,cookies,express,csrf,mean-stack
I have this odd behavior I get an error just the first time my page loads, basically is 'EBADCSRFTOKEN' I've been trying to figure it out why it happens only the first time the page loads, if I hit refresh and get a new token everything works fine. the same...

Design pattern as alternative to front-end template locals

node.js,express,socket.io
I am relatively new to web development and am trying to figure out how to publish the server environment (dev, test, prod, etc) to the front-end. I am using Node.js with Express, but the following code is closer to pseudo-code because is this is more of a design pattern question....

Passport.js - req.session.passport.user is not showing up

node.js,express,passport.js
I am using Passport.js with Express - for some reason the req.session.passport.user value is not present, when it should be, as you can see: here is my passport configuration: passport.serializeUser(function (user, done) { console.log(colors.bgRed('serialize user called, user:', user)); done(null, user._id); }); passport.deserializeUser(function (id, done) { console.log(colors.bgRed('deserialize user called, user_id:', id));...

Unwanted redirect to POST url after successful ajax

javascript,jquery,ajax,express
I do a jQuery ajax POST which successfully delivers the correct data to the server. After the POST is complete, the browser has redirected to the post url page... which I don't want. Neither of the alerts occur. The POST data has arrived at the server just fine. i.e. after...

res.send and res.render calls

javascript,node.js,express
I am trying to determine if i can call res.send(data) and then res.render('reports') simultaneously. To explain further in detail, when i route to '/reports', first on my server side i making a REST call to an API which returns back json data. Now i want this json data to be...

how to determine logged in user in a mean stack application

node.js,express,mean-stack,meanjs
I'm writing an app based on mean.js boiler plate In my server code (express) I need to make some decisions which are based on knowing who the logged in user is I have passport local accounts implemented. How can I determine in the server code the identity of the current...

Using Express' route paths to match `/` and `/index`

javascript,regex,node.js,express,path
I'm using Express and I want to match / and /index to the same route. But if I write app.route('/(index)?') Node throws this error: c:\myproject\node_modules\express\node_modules\path-to-regexp\index.js:69 return new RegExp(path, flags); ^ SyntaxError: Invalid regular expression: /^\/(?(?:([^\/]+?)))?e\/?$/: Invalid group at new RegExp (native) at pathtoRegexp (c:\myproject\node_modules\express\node_modules\path-to-regexp\index.js:69:10) at new Layer (c:\myproject\node_modules\express\lib\router\layer.js:32:17) at Function.proto.route...

Stream read returning empty in nodejs

node.js,express,node-webkit
I am using express to create a webservice that will read string data from a stream, and respond to the HTTP POST request with that value. Here is the code for the S3Store.js file that defines the readFileFromS3(.) function: S3Store.js S3Store.prototype.readFileFromS3 = function(filename, callback) { var readConfig = { 'Bucket':...

Is it possible to send data directly to a constructor?

node.js,mongodb,express
First time using Node.js, Mongodb, Express for web-development. Say you have a constructor 'CreateObject' in a file separate from your routing or driver file. Can I use module.exports.CreateObject, and then simply require and create the object from within the driver, so that I can call a single function and have...

Adding attributes for fields using ejs view helpers

node.js,express,ejs
I am using ejs template rendering <%- input_field_tag('inputFld', 5) %> This code generates input field as <input id="inputFld" value="" type="5" name="inputFld"> Now I want id and name attribute different ie. id="inputFldID" and name="inputFldName" also I want to add class attribute. How should I achieve this?...

How to get ip in socket io

node.js,express,socket.io
var app = require("express")(); var server = require("http").Server(app); var io = require("socket.io")(server); var requestIp = require('request-ip'); server.listen(3000); var ipMiddleware = function(req, res) { return requestIp.getClientIp(req); }; var ip = null; app.get("/", function (req, res) { ip = ipMiddleware(req, res); res.sendFile(__dirname + "/index.html"); }); io.on("connection", function (socket) { // send the...

How to get post params in app.post

node.js,express,ejs
I am developing nodejs project. Where I am using ejs with the help of express-helpers module to generate view template html. in server.js file I have written below code var http = require('http'); var path = require('path'); var async = require('async'); var socketio = require('socket.io'); var express = require('express'); var...

How to rely on other middlewares in express?

node.js,express,middleware
What is the best practice for relying on other middlewares in an express middleware? Let's say my middleware relies on having bodyParser before it executes. Is there a better way than telling my users explicitly in the readme to include and run my dependencies first?

Express - preventing two+ responses from being sent

node.js,express
Using Node.js Express server, we get errors "can't sent headers twice.." if we attempt to send two responses to the same request. I want to figure out the best way to prevent two responses from being sent, for this particular case, but potentially for others as well. I have a...

Secure file upload directly to s3 or server to s3 (from iOS app) [closed]

ios,node.js,amazon-web-services,express,amazon-s3
I need to upload sensitive images to s3 from an iOS app. I'm wondering which option is better: Upload to my server first, then upload to s3. Upload to s3 directly, then upload metadata to my server. ...

Dropzone.js status is pending and not uploading a file

javascript,node.js,backbone.js,express,dropzone.js
I am using Multer in back-end to handle file upload and Dropzone.js in front-end. Everything is fine when I use Postman to test my back-end code, but in when I use Dropzone the status is pending and file not getting uploaded. Then after 4 minutes of waiting I get Timeout...

pass variables to jade template

node.js,express,parameters,parameter-passing,jade
I am trying to pass variables from page.js to page.jade but for some reason this is not working. here's my code: page.js res.render('page', {param1: 'xxx', param2: 'yyy'} ); page.jade #{param1} br #{param2} br ...

Where should I put routes in express.js

node.js,express
I just started to learn node.js with express 4. I have read some books and tutorials, I also cloned some sample apps from git but I still have a very basic question, which practice should I follow to write the routing(or controller)? Some people define all the routes in app.js,...

Redirect user to previous page after authentication

javascript,node.js,express,passport.js
I'm using Google auth through Passport in my app and I'm attempting to redirect the user back to the original page they requested after successful sign-in. I think that location.reload() may be the problem, but not sure how to solve it. routes.js: router.post('/auth/google/return', passport.authenticate('google'), function(req, res) { res.redirect(req.session.returnTo); req.session.returnTo =...

Mongoose: Linked Model Schema “Hasn't Been Registered for Model”

javascript,node.js,mongodb,express,mongoose
Currently using Mongoose with MongoDB for an Express server, however I attempted to link up several Mongoose models together and I am getting MissingSchemaError: Schema hasn't been registered for model "Semester". Use mongoose.model(name, schema) with my execution. The current project structure is as follows app.js www.js models |-- member.js |--...

Refactoring Express Routing

node.js,express
I have many express routes doing similar functionality, with the exception of the .put which handles specific functionality. What would be the best way to refactor this type of code. Require Statements var Ale = require('../models/alert-model.js'); var Service = require('../models/services-model.js'); Routes router.route('/ale/:_id') .get(function(req, res) { Ale.findById(req.params._id, function(err, result) { if...

Confused about nodejs (and the Passport middleware) sessions

node.js,express,passport.js
Super simple question that I'm having trouble wrapping my head around. When using sessions with nodejs, are the sessions stored in the users browser? Or are the sessions stored on the server? For example, if I'm using the express-session or passport.session(), where are these session cookies stored?...

How to know the mount path of router on express?

node.js,express,router
I'm using express' Router on a web application. I'm adding the routers the usual way: app.use(router, '/myroutehere/'); The handlers for each router don't have any idea of where they have been "mounted" (different files, different concerns, etc.). This has worked ok until now that I need to create a ToC...

Error: Cannot GET /

node.js,express,cloud9-ide
I am working in c9.io ide environment, I have written below code in server.js file var http = require('http'); var path = require('path'); var async = require('async'); var socketio = require('socket.io'); var express = require('express'); var express = require('express'); var app = express(); var router = express(); var server =...

Use socket.io-client with Express and nodejs to send query to java server

node.js,express,socket.io
I have a web app built upon Express. The nodejs backend is using a java server to perform some heavy operations. The dialogue between Express and the java server is done using socketio. The nodejs server is the client and uses socket.io-client to send queries to the java server. The...

Select Mongoose Model Based on Express Route

express,routing,mongoose
I think this might be a basic question, but looking for the best approach. I'm building an express app that should route to one of four different Mongoose models depending on the route. Something like this: app.get('/:trial', function(req, res){ var trial = req.params.trial; trial.find(function(err, records) { if (err) res.send(err); res.json(records);...

Node express 404 error HTTP status code

node.js,express,http-status-code-404
I have stripped down my node Express application to the bare minimum. I do not even define routes anymore. When I go to any route, e.g. localhost:3000/sdfsdf, I get the expected output: {"message":"Not Found","error":{"status":404}} The HTTP status code of the response however is 200. I expect it to be 404....

What is the proper regex syntax to use with express routes?

javascript,regex,node.js,express
I'm using regex for express routing and I've hit a roadblock. I have a bunch of tests that get run when a url ending with result is GET. a GET on a string not ending in result returns a list of folders and links to tests. I have a regex...

Why method passed as argument wont work here

javascript,node.js,express
I have this code in my Node/Express API. It works router.get('/auth',function(req, res, next){ var callback = function(redirectUrl){ return res.redirect(redirectUrl); } auth.beginOauth(callback); }); But if I modify this code to something like this. It will not work - router.get('/auth',function(req, res, next){ auth.beginOauth(res.redirect); }); Why when method is passed directly, it wont...

Insert embedded documents Mongo DB from express app

javascript,node.js,mongodb,express,mongoskin
I have a mongo db schema like so users: {username:"", age: "", data: [ {field1:"", field2:""}, {field1:"", field2:""} ] } My problem is how do send over my user object to my express route to post data to the db. Typically i create my user object like so: var user=...

Emitting and receiving socket io within the same file

node.js,express,socket.io
I want to do something where I can set up a route to a link like /visit using app.get('/visit', function(req, res){}) etc. And inside that, I want to emit a message like socket.emit("event", "a message") and then inside my io.on("connection") function, be able to listen for event and return the...

Error handling when uploading file using multer with expressjs

node.js,express,multer,busboy
I am using multer to save the file on server developed through express & nodejs. I am usign following code. var express = require('express'), multer = require('multer') var app = express() app.get('/', function(req, res){ res.send('hello world'); }); app.post('/upload',[ multer({ dest: './uploads/'}), function(req, res){ res.status(204).end() }]); app.listen(3000); Multer saves the file...

How to handle one express route different than all other

javascript,node.js,express,routes
I'm currently using the Express router within a NodeJS application. I have simply been using app.use(app.router); for routing and it works well. However, I'm now testing out some new routes and want to handle them differently. Ideally I would like to be able to say: var vers2Router = require('./routes/version2'); app.use('/version2',...

NodeJS for a JAVA developer - Few Questions

java,node.js,express
I'm working on a project that is heavily based on json. Since 90% of the server side in JAVA would be POJO.toJSON() I decided to give NodeJS a shot! Most of my questions are related to the fact that NodeJS runs as a single thread. Am I right? :) NodeJS...

express.js 4: catch bodyParser error in router's errorHandler

node.js,express,body-parser
How can I catch a bodyParser error in a router's errorHandler in express.js 4? Example code: var express = require('express'); var bodyParser = require('body-parser'); var app = express(); // use bodyParser.json() app.use(bodyParser.json()); // setup route /test var testRouter = express.Router(); testRouter.post('/', function(req, res, next) { next(new Error('not implemented')); }); testRouter.use('/',...

How to include parameters in url using nodejs+jade?

node.js,express,jade
In jade I have two hyper links that both jump to same page, for example: a(href='/signup')#create-account Create Student Account a(href='/signup')#create-admin Create Teacher Account If I want a variable send to '/signup' url and do some processing using that variable, what should I do? Any help will be appreciated....

node user model is vomitting

node.js,express,npm
I am trying to get my hands dirty with making node api following this tutorial https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens problem is that when I execute $ nodejs server.js I get this error { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version {...

Class atributes not updating [node.js - express ]

javascript,node.js,class,express,neo4j
I have some troubles with a .js Object's atribute which is not updating when i ask it to. I'm new in the javascript world, so i hope my issue won't be tricky. First of all, this is a part of my Node class : Node = function (label, vals, db,...

getting form data in node js:undefined error while submitting form

javascript,node.js,express
I am trying to get data from a form using express js.But i will get an undefined error in my console. here is my html <form action="/login" method="post"> <label>Username</label> <input type="text" name="username" value=""><br><br> <label>Password</label> <input type="password" name="password" value=""><br><br> <input type="submit" name="" value="Login"> </form> index.js var app = require('express')(); var url...

Express Router Prefix

node.js,express
I am confused about how to properly set up API routing in my express app. What I would like to have is structured way to define routes without repeating myself. As a database I am using RethinkDB. For each model, let's say Exercise I have created a file in the...

How to handle expressjs middleware request. post request remains pending made by dropzone

node.js,express,dropzone.js,multer
I am using dropzone to upload the file. On the server side I am using node and expressjs. I am also using multer as the file handling middleware. dropzone makes a call to one endpoint to save the file on the server. On the server side, I created an endpoint...

zip and download from nodejs

node.js,express,download
I am trying to zip the file and download from server using easy-zip module. But now I can write into a server using following code but how can i make it downloadable??? var app = require('express')(); var easyzip = require('easy-zip'); app.get('/api/downloadFile',function(req,res){ console.log("inside req"); var data = "<html><body><h1>Inside new Html</h1></body></html>"; var...

How should i use req inside non-middleware (Passport.js)?

node.js,express,passport.js
I want to update user's ip every time he or she logs in. I was informed that only middlewares get req, res, and next parameters, but I am using passportjs, which should come first to authorize the user. How should I update user data? Below is my code block of...

404 on api authenticate for node restful

node.js,express,npm
I am using this tutorial https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens to learn about node with restful authentication. I am getting 404s in the route when I post at this http://localhost:8090/api/authenticate Here is the response that I get Cannot POST /api/authenticate and the console shows 404 POST /api/authenticate 404 2.465 ms - 30 here is...

How to create subdomain for user in node.js

javascript,node.js,express
I'd like to share some user information at username.domain.com at my application. Subdomain should be available after user create his account. I have found nice module that could be useful in that case: Express Subdomain How can I do it properly using that module? Maybe this module isn't so useful...

Ejs input_field_tag method setting type attribute as 5

node.js,express,ejs
I am using ejs for template rendering, I am using below code <%- input_field_tag('empName', 5) %> Which generates output as <input id="empName" value="" type="5" name="empName"> Here the type attribute is set as 5 -- Which actually need to be set as text and value attribute need to be set as...

How to use passport.js's TwitterStrategy sessionless?

node.js,express,passport.js
I tried to implement TwitterStrategy like it's done with Facebook in: Token based, sessionless auth using express and passport But express still wants me to use session middleware: {"message":"OAuthStrategy requires session support. Did you forget app.use(express.session(...))?" Can someone provide a detailed example? ...

My POST from html does not return any value, nodejs, express

html,node.js,express
I am trying to do a simple post from html page and when I check the console after the post it returns nothing. I have the body parser used correctly on the server side. Is there something that I am doing wrong? var http = require('http'); var fs = require('fs');...

What is wrong with Nodejs?

node.js,express,runtime-error,middleware,multer
I am using multer to handle upload image. app.use(multer({ dest: './public/photos', rename: function (fieldname, filename) { return filename+Date.now(); }, onFileUploadStart: function (file) { console.log(file.originalname + ' is starting ...') }, onFileUploadComplete: function (file) { console.log(file.fieldname + ' uploaded to ' + file.path) //a='asass'; done=true; } })); app.post('/api/photo',function(req,res){ if(done==true){ //ERROR here...

Node forward path request to another server

node.js,express,routing,routes,request
Currently have a website running a node server that handles all requests for example.com and I created a completely separate wordpress blog on a separate server (running apache) that I would like served on a path like example.com/blog at 172.23.23.23 IP address. The wordpress server doesn't share any code or...

How to redirect and then stop in node.js

javascript,node.js,redirect,express
I am trying to stop users accessing certain pages whilst logged in and not logged in with node.js. So far I have this idea: exports.blockIfLoggedIn = function (req, res) { if (req.isAuthenticated()) { //passport req.flash('error', 'Sorry but you can\'t access this page'); res.redirect('/'); } }; MA.f.auth.blockIfLoggedIn(req, res, next); res.render('users/login', {...

Live updating Node.js server

javascript,node.js,express
I want to design a live updating Node.js Express server, perhaps having a particular route, say /update, which loads a new configuration file. The only concern I have with this right now is that the server could potentially be in any state when the update happens. If I load a...

Include whole directory of scripts using Jade?

javascript,node.js,express,jade
Is it possible to include a whole directory of scripts with Jade? My current scripts.jade file looks like this: script(type="text/javascript", src="/vendor/angular.js") script(type="text/javascript", src="/vendor/angular-resource.js") script(type="text/javascript", src="/vendor/angular-route.js") script(type="text/javascript", src="/core.js") I was hoping from something like this: script(type="text/javascript", src="/vendor/*.js") or this: <!-- include: "type": "js", "files": "/vendor/*.js" --> Any ideas?...

Express get error

node.js,model-view-controller,express
I am setting up routes to my application controller on a node server - var http = require('http'); var app = require('express')(); app.get('/<path>/<query type>', function(req, res) { //Expecting query parameter <query type>?name=<something> var query = req.query.name; var path = '/<path>/<query type>?name='+query; var options = { host: 'localhost', port: 8080, path:...

Bonsai automatic indexing

mongodb,heroku,express,elasticsearch,bonsai-elasticsearch
I use MongoDb for storage with an express, Heroku-hosted app. I would like to provide search capabilities to some MongoDb collections, using ElasticSearch via the Bonsai Heroku add-on. However, according to the Bonsai faq, Elasticsearch River plugins are not supported. How can I automatically re-index my MongoDb collections (when a...

include a view file that it's name is in a variable into an EJS template

javascript,node.js,express,ejs
I use this method to include an ejs file in my template: <% include header %> But if header is a variable, I get some errors. How i can include a file that it's name is in a variable into an ejs template?...

logging message on chrome console in expressjs - MEAN Stack

javascript,google-chrome,express,mean-stack
I have a created routes and calling some functions in expressjs. This function is properly getting executing and retuning data. exports.index = function (req, res) { Data.find({ parent: null }, function (err, employee) { if (err) { return handleError(res, err); } return res.status(200).json(employee); }); }; I want to log some...

Req.files in undefined at the server side (built with express & node) when sending files using dropzone

node.js,express,dropzone.js
I am using dropzone to upload files from the UI. Here is my drozone configuration: var imageUpload = new Dropzone('div#dataSection', { url: 'api/image', autoProcessQueue: true, paramName: 'file' }); I am using node and expressjs to build the server side endpoint based on this link I am excuting below code on...

What is the best framework and difference of nodejs framework

node.js,express,faye
These days I try to develop real time application using nodejs. That application want to update the dashboard according to api data. I installed express and faye and try to compare what is the best and what are the differences of that two. As I know express is a node...

NodeJS / ExpressJS check valid token parameter before routing

node.js,express,parameters
I have the following app code: (app.js) var express = require('express') , app = express() , port = process.env.PORT || 8082 app.use(require('./controllers')) app.use(function(req, res, next) { res.send('Test') next() }) app.listen(port, function() { console.log('Listening on port ' + port) }) and two controllers: (index.js) var express = require('express') , router =...

NODE/EXPRESS/PASSPORT - Facebook App with Callback URL

node.js,facebook,express,callback
I am creating a facebook app. And I want to let users to login to my website using FB. I have integrated the code but FB cannot found the callback page/url. URL: http://www.mywebsite.com:3000/auth/facebook/callback?code={here_goes_the_callback_code} Error: The webpage cannot be found app.js var express = require('express'); var routes = require('./routes'); var http...

Override file doesnt work in node js

javascript,node.js,express
I've file which I was able to read and get the data and now I want to override the file content but what I try below doesn't work am I missing something ? var str = "t123"; fs.writeFile('C:\\test.txt',str,'utf8',{'flags': 'a+'},function(){ fs.readFile('C:\\test.txt', 'utf8', function (err,data) { console.log(data === str) res.send(data); }); });...

Node Server - Source Code accessible

node.js,express
I noticed that when i navigate to localhost:8080/server.js (where my server.js is the server-expressjs obviously) the code of my server is shown in the browser! Even, if i upload the application to openshift, i get the same result (you can test it): http://tickets-shkobba125.rhcloud.com/ http://tickets-shkobba125.rhcloud.com/server.js Is this a security issue? How...

Jade / Expressjs: Pass objects from server to client

javascript,node.js,express,jade
I'm trying to pass an object from my endpoint to Jade but It keeps giving me Uncaught SyntaxError: Unexpected identifier on Stat! Can someone help me please. Here is my code: app.get('/stats', function (req, res, next) { var stats ={ 'm0t20': {a:0,b:0,c:0,d:0}, 'm20t30': {a:0,b:0,c:0,d:0}, }; res.render('chart',{'stat':stats}); } and in my...

Redis: Delete user token by email ( find Key by Value )

node.js,express,redis
I have followed tutorial on how to create token-based authentication with node from this tutorial http://www.kdelemme.com/2014/08/16/token-based-authentication-with-nodejs-redis/ I got it all worked out, but I got 1 problem. The way I store token is : KEY = TOKEN VALUE = UserData (Username, email, etc.) To protect multiple devices login, I would...

ExpressJs is not serving index.html

javascript,angularjs,express
I have an Angular client application that runs entirely in the browser. I am trying to use expressjs to host it. I modeled the server code after the server.js in John Papa's MEAN Hot Towel application that he uses in his Pluralsight Gulp course. This is my server code: var...

Express js 4, Parse.com JSON error

javascript,jquery,node.js,express,parse.com
I am trying to send a POST call to an Express JS server hosted on Parse.com. I send the data like this: var data = new Array(); data["firstName"] = firstName; data["lastName"] = lastName; data["dateOfBirth"] = dateOfBirth; data["mobileNumbe"] = mobileNumber; data["email"] = email; data["reEmail"] = reEmail; data["pw"] = pw; data["rePw"] =...

pretty print json directly in page from Express

json,object,express
I'd like to pretty print a large javascript object in my browser window using Express. I've tried res.json() and res.send() with pretty print turned on in express, but it looks like that only works for html and not objects. The response is only the javascript object which is all I...

Using middleware to call an Authentication API using ExpressJS

angularjs,node.js,authentication,express
I'm using two Node.js + Express applications: Backend Authentication And my front-end is built in AngularJS Basically I'm trying to send a json web token with every request to the Backend, and then use a route middleware to call the Authentication API. It validates that token and add user data...

Comparison Express JS, Angular JS vs Backbone JS [closed]

angularjs,backbone.js,express,requirements
I am starting to learn node js for a while and it seem amazing. When I start to apply nodejs to build a scalable website, I am wondering to do Express for back-end, BackBone Js or Angular JS for front-end, people said Express JS is very fast, while Backbone.js seem...