javascript,node.js,express,routes
As of Express version 4.x, app.router has been removed. Routes are now executed in the order they are added. Now you may use the express.Router because it will allow you to have isolated instances of routes and in your example you could create many routers with their own versioned routes....
You can write your route files like so: module.exports = function (app) { 'use strict'; var router = express.Router(); router.get('/', getAllExercises); router.get('/:id', getExerciseById); app.use('/api/exercises', router); }; And require each of them like this: require('./routes/exercises')(app); Note that you can replace __dirname + '/... with './.......
You can check for res.headersSent if (res.headersSent) return; client.info(function (err, resp) { //this callback will also invoke res.send if (res.headersSent) return; response['redisInfo'] = resp; res.status(200).send({"test message from SmartConnect": response}); }); ...
So after many hours of fiddling and reading I replaced this code: app.use(express.static('./src/app')); app.use(express.static('./')); app.use(express.static('./temp')); app.use('/*', express.static('./src/index.html')); with this: app.use(express.static(__dirname)); app.use(express.static(process.cwd())); app.route('/*') .get(function(req, res) { res.sendFile(__dirname + '/index.html'); }); and it appears to have solved the problem...
"what is doing the 'posting'" When a Form gets submitted, it's that which does the 'POSTing'. A "submit" is an action, like a function call, not simply a boolean value being watched for true or false. <form method="POST" action="/url"> <input name="name" value="value"> <button>Submit</button> </form> Here when the button will...
You can handle errors using the onError option: app.post('/upload',[ multer({ dest : './uploads/', onError : function(err, next) { console.log('error', err); next(err); } }), function(req, res) { res.status(204).end(); } ]); If you call next(err), your route handler (generating the 204) will be skipped and the error will be handled by Express....
You can get models by name: var mongoose = require('mongoose'); app.get('/:trial', function(req, res){ var trial = req.params.trial; mongoose.Model(trial).find(function(err, records) { if (err) { // Return when we end the response here... return res.send(err); } res.json(records); // returns all trial records in JSON format }); }); Depending on circumstances, I would...
javascript,node.js,express,routes
Method routes (.get, .post, and of course .all) are terminal. This is why you can use wildcards with them as well. .use is not terminal and doesn't allow wildcards -- it acts as a prefix. This is an implementation choice of express. Use .use without wildcards. .use does not set...
javascript,jquery,node.js,express,parse.com
There's a typo in your express code. You're referencing req.data when it should be req.body.data: For instance, this: var user = new Parse.User(); user.set("username", req.data.email); user.set("password", req.data.pw); user.set("email", req.data.email); Should be this: var user = new Parse.User(); user.set("username", req.body.data.email); user.set("password", req.body.data.pw); user.set("email", req.body.data.email); Also, your initial data array is actually...
angularjs,node.js,express,mongoose,passport.js
So apparently the problem is that HTML defaults to finding an index.html file in any folder within the root. When I change the html file to something else like abc.html the problem is solved. Seems like a bug to me.
node.js,express,runtime-error,middleware,multer
What done=true is doing, is declaring a global variable called done. In order for it to not be a global variable, use the var key word e.g. var done = true. It is generally regarded as a bad idea to declare global variables. JavaScript has an optional mode called strict...
The callback from toArray is asynchronous, i.e. will happen after your console.log line executes, therefore you need to re-arrange as follows: var collectionOne = []; router.get('/fetch',function(req, res, next){ MongoClient.connect('mongodb://localhost:27017/local', function(err, db){ var collection = db.collection('borrower'); db.collection("borrower", function(err, collection) { collection.find().toArray(function(err, result) { if (err) { throw err; } else {...
javascript,node.js,backbone.js,express,dropzone.js
I solved the issue by enabling Cache-Control in Access-Control-Allow-Header header of my Node server. app.use(function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Cache-Control, Origin, X-Requested-With, Content-Type, Accept, Authorization'); res.header('Access-Control-Allow-Methods', 'GET,PUT,PATCH,POST,DELETE'); if (req.method === 'OPTIONS') return res.end(); next(); }); ...
javascript,node.js,express,ejs
You can't: https://github.com/tj/ejs/issues/93 The issue was opened in 2013 and never resolved. However, in version 2 you call include as a plain function: <%- include(header) %> ...
Disclaimer: I have not tried this in production. In fact, I have not tried this at all. while I believe the idea is sane, there may be hidden pitfalls along the road which are not currently known to me. There is one thing that many Node.js developers tend to...
It depends on whether you will make your app to be RESTful or not. Saying you would like to be Restful. To create an admin you should make a POST to the url /admin. Respectively to create an account you should post to the url /account. This is if admin...
From Passport twitter middleware issue reported earlier on gihub Any OAuth 1.0 strategy requires sessions. OAuth 2 requires it if state is enabled (which is highly recommended). A temporary secret is stored in the session to prevent cross site scripting attacks. ...
angularjs,node.js,authentication,express
It looks like the middleware is being fired from the OPTIONS request. Using a more robust express library like cors will solve this problem. Alternatively, you could check for the OPTIONS request manually, then return the necessary information instead of calling next(), but unless you know exactly what you're doing,...
Depending on what you're going for using browser extensions or a program like Postman will make it easier for you to develop against.
When a browser asks the server for a request with a GET, it sends an ACCEPT statement in the header information. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation#The_Accept.3A_header So, I'd guess that your browser makes its request and says to the server (in its header) "I can accept graphics files, video files, HTML files, text...
Streams in node.js are not synchronous - they are event driven. They just aren't synchronous. So, you can't get their results into a string synchronously. If you have no choice but to use a stream, then you have no choice but to deal with the contents of the stream asynchronously....
Express doesn't really care about constructors or objects. You can certainly use them, but then you need to do some plumbing to use them within a middleware function. Instead, you might want to think in terms of middleware functions. A common pattern in node development is to define one (or...
Multer is it's own middleware. You can add it to a route via: router.post('/uploads', multer({ dest: './my/destination' //req.app.get('cfg').uploads.dir }), function (req, res, next) { console.log(req.files); process.exit(); }); Though you're going to have to find another way to access your config. One way would be to pass the config or app...
you can use something like this . I am using a socket.io method to get the client ip address here . io.on("connection", function (socket) { var clientIp = socket.request.connection.remoteAddress; socket.emit('eventName',{ip : clientIp}); //emit it back to client }); check this stackoverflow thread to know how to get client ip for...
you should use a middleware such as body-parser var bodyParser = require('body-parser'); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.post('/demo', function (req, res) { console.log(req.body) }); ...
Try zip2.writeToResponse(res,'folder.zip'); instead of zip2.writeToFile('folder.zip');
You are probably looking for text_field_tag, because type="5" doesn't make much sense. You can pass object as third argument to text_field_tag with attributes you want to set. <%- text_field_tag('inputFld', '5', {id: 'inputFldId', Class: 'some_class'}) %> ...
The problem is that your middleware will only be called on routes that include the :id param, because you have it mounted on '/players/:id/info'. You'll need to mount it on '/players' in order to match both cases.
Could be that the execution context is different. When you say res.redirect(redirectUrl), this inside the redirect method is referring to the res object(unless a custom execution context is used), but when you pass res.redirect as a callback, when the callback is invoked the context is lost. router.get('/auth',function(req, res, next){ auth.beginOauth(res.redirect.bind(res));...
javascript,node.js,class,express,neo4j
.save is asynchronous, so you can't use the value returned by it outside its callback, hence moving the rest of your code inside the callback will fix it: var t = this; this.db.save(vals, function (err, node) { if (err) throw err; vals = node; console.log("2:"); // output print console.log(vals); //...
1) Node is using Javascript so it is single threaded and non-blocking. 2) If i understand correctly what you mean.. yes you can have a single file application. Which probably make your life miserable when the app grows big. 3) Yes.This variable will be accessible through out the file. For...
Use a middleware. app.use(function (req, res, next) { if (checkToken(req.query.token) { return next(); } res.status(403).end("invalid token"); }); app.use(require('./controllers')) ...
javascript,json,angularjs,node.js,express
Relative paths (starting with ../ or ./) are relative to the current working directory. If you want to read a file relative to the current JS source file, you need to prefix the path with __dirname, which is the directory where the current JS source file resides: fs.readFile(__dirname + '/../testJSON/user.json',...
node.js,cookies,express,csrf,mean-stack
I believe you are not using csurf correctly, csurf sets the cookie for you, you should not set it yourself, and its value is different from csrfToken() value. As far as I understand from docs and source code csrfToken() value is generated using the value that csurf sets for the...
javascript,node.js,redirect,express
You should use middleware. Here's an example: // you can include this function elsewhere; just make sure you have access to it var blockIfLoggedIn = function (req, res, next) { if (req.isAuthenticated()) { req.flash('error', 'Sorry, but you cannot access this page.') return res.redirect('/') } else { return next() } }...
javascript,node.js,express,node-http-proxy
http.createServer(function(req, res) { res.end("Request received on 9001"); }).listen(9056); Your HTTP server is listening on port 9056. The proxy tries to connect to a HTTP server on wrong port and throws an error, when connection cannot be established. To avoid errors like this on the future, put port in a variable:...
node.js,express,dropzone.js,multer
You need an Express route for your form post that will finish the http request. The multer middleware will process the file uploads and add them to the request so they are available to a route handler, but you need to have a route for the form post. From the...
node.js,express,routing,routes,request
This works: here's what you need to put in your node app: var express = require('express'); var app = module.exports = express(); var proxy = require('http-proxy').createProxyServer({ host: 'http://your_blog.com', // port: 80 }); app.use('/blog', function(req, res, next) { proxy.web(req, res, { target: 'http://your_blog.com' }, next); }); app.listen(80, function(){ console.log('Listening!'); }); Then...
You basically have to choose one of two approaches: a full scan of the database or an index. A full scan, as proposed in another answer to this question, will be quite inefficient - you'll go over your entire keyspace (or at least all the tokens) and will need to...
javascript,node.js,express,jade
If you want to interpolate object from you express, the easiest and cleanest way is to serialize them. For the moment, once interpolated, you are trying to write something like this: var stats = [Object object]; Which isn't a valid JavaScript syntax :/ So, on the server side, serialize your...
node.js,express,http-status-code-404
res.status(err.status || 500); res.status('error').json({ you finally override res.statuscode with 'error'. change to res.status(err.status || 500); res.json({ ...
The structure of your controller is a bit messed up. Here are some things that are wrong: You connect to the Java server when the module is loaded, but you don't assign a connect event handler until the route gets hit. This means you will normally miss the connect event...
The tutorial you were following is quite outdated, and certainly written for old version of express. With express 4.0, released in April 2014, (almost) all built-in middleware was dropped, including the one parsing uploaded files as req.files. That's the problem, and the solution is to use separate module to handle...
This is completely preferential. Any pattern that works is likely to be valid here. Express routers make things very nice and easy to setup. Personally I prefer to create a directory for every top level route, files for the second level, and exports for the third. Here's an example of...
javascript,angularjs,node.js,express,multer
OK so after battling with this all day i've got a dirty fix that works so i thought i'd share it with you, but there really must be a cleaner, more elegant way of doing this: app.post('/api/photo',function(req,res){ if(done==true){ photoName = req.files.userPhoto.name; photoName = encodeURIComponent(photoName); res.redirect('../course?img=' + photoName); } }); Just...
I don't believe that combining express.js (simple web server for Node.JS platform) and Apache Tomcat (Servlet container from JVM world) make sense at all. I bet that you are confusing Apache Web Server with Apache Tomcat. They are two completely separate projects. If that is the case than notice that...
node.js,facebook,express,callback
If you just want to log the successful login then put this in your app.js for the route to home: router.get('/home', isAuthenticated, function(req, res, next) { console.log('GET /home login success for [%s]', req.user.username); res.render('home'); }); If you also want to greet the person on your home page by username... Somewhere...
mongodb,heroku,express,elasticsearch,bonsai-elasticsearch
Here is the answer by Bonsai support: - You could always set up a script with a curl command to index the MongoDB collections, then use cron to run the script at regular intervals. - You could also use an Elasticsearch client to index collections in some cases. So I...
They are not very comparable. If you want to create a real-time application, you will probably need to use both. Express is a web framework. You will need it to serve and handle HTTP requests and responses. It will help you handle things like url routing, request/response handling middleware, interfacing...
In most environments, including Windows, it is useful for setting the startup file. This startup script will execute the Node.js process that runs on the server. There is typically a #! on this executable file. Like: #!/usr/bin/env node // Code to bootstrap your web application ...
What about "router.mountpath"? http://expressjs.com/api.html#app.mountpath Upd. Ok, you need: <req.route.path>, <req.baseUrl>, <req.originalUrl> ...
javascript,node.js,mongodb,express,mongoose
This error could be happening because you're requiring Member model before Semester in app.js, this is because Semester model and schema not exist when './models/member' is required Try to change the order in app.js to: // MODELS require('./models/semester'); require('./models/member'); To avoid this situation you could require the model from the...
This would work, but what's the gain vs // B app.get('/', function(req, res) { res.json({ info: info, html: template.render(info) }); }); or // C socket.on('get-index', function () { socket.emit('index', { info: info, html: template.render(info) }); }); or with the template moved client side, simply return the info. Once an intelligent...
javascript,ajax,angularjs,express
In Angular this can be solved with an interceptor. See Angular-loading-bar as example.
This answer was mostly resolved in the comments. Here was the final solution. First, the project directory was incorrect and the file being required was not where it was supposed to be. Fixing the require statement fixed this issue. Second, the server was not able to connect to the mongodb...
I created an example for showing how I could manage this scenario. The directory tree of the project, where public directory contains the public assets and inside there is a protected directory for storing the protected asssets. ├── app.js └── public ├── index.html └── protected └── app.html In the app.js...
I'm not having issue with this code: var app = require('express')(); var server = require('http').Server(app); var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.post('/login',function(req,res){ console.log(req.body); console.log("server"+req.body.username+req.body.password); }); var server = app.listen(3000); And testing with: curl 'http://127.0.0.1:3000/login' --data 'username=zetg&password=zetgze' I don't know what is wrong with your code, but try...
If you are trying to emit and listen for events within the same file, you should be using the built in event listeners for node, not the specialized ones for socket.io (https://nodejs.org/api/events.html): var EventEmitter = require('events').EventEmitter; var eventExample = new EventEmitter; //You can create event listeners: eventExample.on('anEvent', function(someData){ //Do something...
javascript,node.js,express,jade
There is no possibility to use such wildcards in Jade, it has no such notion of your filesystem. You can create a mixin that will help a bit though, for example: mixin scripts(path, names) - each name in names script(type="text/javascript", src=path+name+".js") +scripts("/vendor/", ["angular", "angular-resource", "angular-route"]) For the possibility of automatical...
Try using app.use(bodyParser.urlencoded({ extended: true })); instead of app.use(bodyParser.json()) ...
You need to have testRouter use the body parser middleware: // not this: app.use(bodyParser.json()); // but this: testRouter.use(bodyParser.json()); Otherwise the default router will handle the error, like you noticed. If you also want to use the body parser middleware for the default router, make sure that you declare it after...
javascript,node.js,express,reactjs,passport.js
Split a view rendering path from API paths. After all you can set the authentication logic into api calls. //Auth check middleware function isAuth(req, res, next) {...} //API routes app.post("api/users/login", function() {...}); app.post("api/users/logout", function() {...}); app.get("api/purchases", isAuth, function() {...}); //and so on... //Wild card view render route app.use(function(req, res) {...
You are probably using express-helpers module which uses different arguments than plain ejs view helpers. The input_field_tag in express-helpers module takes name as the first argument, inputType as the second one and third is options object. See wiki of this module for more information....
You're logging the data but you're not passing anything to the completion callback (see below for some more explanation): S3Store.prototype.readFileFromS3 = function(filename, callback) { var readConfig = { 'Bucket': 'shubham-test', 'Key': filename }; var readStream = this.s3.getObject(readConfig).createReadStream(); var allData = []; // Keep collecting data. readStream.on('data', function(data) { allData.push(data); });...
The obvious answer is to change the directory used in the express.static() middleware if you're using that. Typically there is a public or similarly-named directory that you would create that holds only your public assets. Remove the app.use(express.static(__dirname + '/'));, this is what is allowing your code to be public....
javascript,node.js,express,handlebars.js
The value of user.name needs to be output as a valid JavaScript expression if you want to include it in within a <script>, which will be reevaluating it as code. Currently, if user.name is "john.doe" for example, the resulting script will be: var foo = john.doe; // `john` is treated...
angularjs,backbone.js,express,requirements
Express is for backend servers. So it can be compared to other languages' frameworks such as Sinatra (Ruby), Django (Python), etc. Backbone is a minimalist frontend framework, comparable to others in the game such as Ember.js, Angular, etc. The main difference is that Express runs on a server and Backbone...
javascript,regex,node.js,express,path
The question mark is for optional route parameters, not optional route segments. For example: app.route('/:myVar?'); With app.route('/(index)?'); you are matching routes that are literally "http://myapp.com/(index)". You want a regular expression route. app.route(/^\/(index)?$/); ^ - matches the beginning of a line, so that the whole expression must match from the beginning....
javascript,node.js,unit-testing,express,sequelize.js
I created some files for mocking up: User, jwt, also created two additionals for your route, and the test itself. You can see here all the files, if you want to run you need first install mocha and q: npm install mocha npm install q and the run: mocha so...
javascript,node.js,mongodb,express,mongoskin
at the moment when you are configuring express, review if you are using this line of code: In case you are using Express 4.x version Note: you need to have body-parser installed. app.use(bodyParser.urlencoded({ extended: true })); In case you are using Express 3.x version app.use(express.urlencoded()); I did a test example...
node.js,express,parameters,parameter-passing,jade
You might be rendering them as tags instead. View your source html post render. Try using !{param} instead of #{param}....
node.js,model-view-controller,express
You need to initialize your app like this var app = require('express')(); ...
The fine manual states: Note Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side. express-session sends a cookie to the browser (which stores it), which contains a unique session id. The data itself is stored on the server (depending on which...
ios,node.js,amazon-web-services,express,amazon-s3
You want to choose option 2, have your user upload directly to S3. If you use option 1, you have the possibility of your server going away before it can complete the upload to S3 (think autoscaling, where an instance is taken out of service before it can complete). And...
javascript,regex,node.js,express
Apparently the syntax is pure regex. Who would have known! I'm currently using: router.get(/[\w\/:]*result$/, [function (req, res, next) { router.get(/^(?![\w\/\:].*result$)/, function (req, res, next) { and it works like a charm. Still haven't figured out how to get variables in there. But it works for now....
First, you should type heroku config to get your clearDB credentials. Then, you can ran this command from your terminal : mysql --host=us-cdbr-east.cleardb.com --user=xxxx --password=xxxx --reconnect heroku_xxxxxx < schema.sql...
You could use content negotiation for that, where your AJAX request sets the Accept header to tell your Express server to return JSON instead of HTML: router.get('/reports', function(req,res) { ... if (req.accepts('json')) { return res.send(theData); } else { return res.render('reports', ...); }; }); Alternatively, you can check if the request...
You can configure BasicStrategy to pass the request as first argument: passport.use( new BasicStrategy({ passReqToCallback : true }, function(req, username, password, callback) { ... }) ); This (sadly) isn't well documented, but I believe most Passport strategies support it (see also)....
javascript,google-chrome,express,mean-stack
This is a server site javascript so you need to look at the nodejs console.
I don't know if this is the only issue, but you're calling this: var io = require("socket.io").listen(app); before you assign the app variable so it is undefined. The request for this URL: http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1434334401655-37 is how a socket.io connection starts so that is normal. The problem is that the socket.io listener...
node.js,mongodb,express,mongoose
Basically, you could use any solution for async control flow management like async or promises (see laggingreflex's answer for details), but I would recommend you to use specialized Mongoose methods to populate the whole array in one MongoDB query. The most straightforward solution is to use Query#populate method to get...
node.js,express,jasmine,supertest
request(app.app) instead of request(app) in integration test should fix the error. var request = require('supertest'); var app = require('../app'); describe('GET /', function(){ it('should repsond with 200', function(done){ request(app.app) .get('/') .expect(200, done.fail); }); }); ...
If you go into config/express.js you will see something like this: app.use(express.static(path.join(config.root, 'public'))); Which should be self-explanatory. UPD. With routes you can overwrite this behaviour for specific files (if you really need it)....
Try to .toObject() the form: Form.findOneAndUpdate(condition, req.body, {upsert:true}, function(err, form){ if (err) return res.send(500, { error: err }); var objForm = form.toObject(); objForm.status = "saved successfully"; return res.send(objForm); }); ...
javascript,node.js,express,postman
If you want to add a custom content type then you need to keep two things in mind: Content type couldn't be "application/text/enriched", in other hand "application/text-enriched" is ok. Max two "words". You must provide a custom accept header on body parser configuration BUT body parser return you a buffer...
javascript,node.js,express,ejs
You are calling res.render in the wrong place (data will only have its value later, when request will send its end event. So you need to move the res.render inside the end event callback. Try response.on("end", function (err) { // finished transferring data // dump the raw data var data...
node.js,express,mean-stack,meanjs
If you are using passport you just have to access req.user as it was already mentioned. Taking a look at your gist, my guess is that some of your routes are defined much earlier than app.use(passport.initialize()); and app.use(passport.session());, which means that if you receive a request to get /opportunity_ids (for...
javascript,angularjs,node.js,express
Looks like there are least two problems in your controller. You have res.status(404).send({err: 'User Not Found.'}); followed by res.redirect('/login');. Both send and redirect finish the request and respond the request, so that's basically like trying to respond twice. That's probably what is giving you the "can't set headers" error. This...
node.js,express,gruntjs,mean-stack
Express is a webserver framework on top of nodejs (like symphony for php). Grunt is an automation tool (like make or gulp) and not a webserver. The only thing they have in common is, that they use the JavaScript programming language. MEAN is a full stack environment for developing web...
angularjs,node.js,express,mean-stack,meanjs
You need to use angular.toJson method like this: $scope.postUpdate = function(){ console.log('kwRequired ' + $scope.kwRequired); var postData = {kw: $scope.kwRequired}; var json = angular.toJson(postData); $http.post('/salesforce_update', json); } Also make sure to define app.use(bodyParser.json()); before the definition of app.post('/salesforce_update', function .... ...
You need to actually use the apiRoutes like this .... .... app.use('/api', apiRoutes); // ======================= // start the server ====== // ======================= app.listen(port); console.log('Magic happens at http://localhost:' + port); ...
Create a small util lib for yourself, which will act as a function factory. Take those two router.route('/ale/:_id') .get(function(req, res) { Ale.findById(req.params._id, function(err, result) { if (err) res.send(err); res.json(result); }); }) router.route('/ser/:_id') .get(function(req, res) { Service.findById(req.params._id, function(err, result) { if (err) res.send(err); res.json(result); }); }) You could do this var...
javascript,node.js,express,passport.js
Try: router.post('/auth/google/return', passport.authenticate('google'), function(req, res) { var backURL = req.header('Referer') || '/'; res.json({redir: backURL}); }); And: $.post('/auth/google/return', {code: authResult.code, access_token: authResult.access_token}).done(function(data) { window.location.href = data.redir; }); ...