Menu
  • HOME
  • TAGS

Bonsai automatic indexing

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...

How to handle one express route different than all other

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....

NodeJS for a JAVA developer - Few Questions

java,node.js,express

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...

Csurf invalid csrf token Express / nodejs

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...

NodeJS / ExpressJS check valid token parameter before routing

node.js,express,parameters

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')) ...

Need to send response after forEach is done

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 forward path request to another server

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...

How to validate presence of parameter in API call

javascript,node.js,express

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.

Write NodeJS stream into a string synchronously

node.js,express

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....

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

mysql,heroku,express,cleardb

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...

Send code via post message is not working

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...

How to get post params in app.post

node.js,express,ejs

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) }); ...

ExpressJs is not serving index.html

javascript,angularjs,express

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...

Dropzone.js status is pending and not uploading a file

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(); }); ...

logging message on chrome console in expressjs - MEAN Stack

javascript,google-chrome,express,mean-stack

This is a server site javascript so you need to look at the nodejs console.

how to determine logged in user in a mean stack application

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...

Get local json file using request-promise

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',...

Express Router Prefix

node.js,express

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 './.......

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

html,node.js,express

Try using app.use(bodyParser.urlencoded({ extended: true })); instead of app.use(bodyParser.json()) ...

res.send and res.render calls

javascript,node.js,express

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...

unable to add property to the json object

node.js,express,mongoose

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); }); ...

Refactoring Express Routing

node.js,express

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...

NodeJs + ExpressJs app routing odd behavior

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.

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

node.js,express,dropzone.js

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...

Why method passed as argument wont work here

javascript,node.js,express

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));...

Is it possible to send data directly to a constructor?

node.js,mongodb,express

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...

Ejs input_field_tag method setting type attribute as 5

node.js,express,ejs

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....

Emitting and receiving socket io within the same file

node.js,express,socket.io

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...

Live updating Node.js server

javascript,node.js,express

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...

How to rely on other middlewares in express?

node.js,express,middleware

If your middleware requires body-parser and it would insert that middleware into the middleware chain itself, it may become problematic when the user is already including body-parser in their app (in other words, body-parser would be included twice). It may work (never tried), but it may also cause unintended side...

node user model is vomitting

node.js,express,npm

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...

Insert embedded documents Mongo DB from express app

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...

Error: Cannot GET /

node.js,express,cloud9-ide

You seem to have created two instances of express which may be your problem. Try changing: var express = require('express'); var app = express(); var router = express(); var server = http.createServer(router); to: var express = require('express'); var app = express(); var server = http.createServer(app); At the minute, your express...

How to know the mount path of router on express?

node.js,express,router

What about "router.mountpath"? http://expressjs.com/api.html#app.mountpath Upd. Ok, you need: <req.route.path>, <req.baseUrl>, <req.originalUrl> ...

Where should I put routes in express.js

node.js,express

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...

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

node.js,express,passport.js

It was hard to find an answer for this online, so I think one should go here. The problem was because instead of using this: app.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' })); ...I decided to use this style of call with Passport: app.get('/login', function(req, res, next) { passport.authenticate('local', function(err,...

What is the best framework and difference of nodejs framework

node.js,express,faye

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...

Include whole directory of scripts using Jade?

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...

How to create subdomain for user in node.js

javascript,node.js,express

As I mentioned in OP comments, using Nginx webserver in front of Node would be very good option, since this is a secure way to listen 80 port. You can also serve static files (scripts, styles, images, fonts, etc.) more efficiently, as well as have multiple sites within a single...

How to redirect and then stop in node.js

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() } }...

Adding attributes for fields using ejs view helpers

node.js,express,ejs

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'}) %> ...

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

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...

Express.js server with Apache Tomcat

node.js,tomcat,express

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...

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

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...

What is wrong with Nodejs?

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...

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

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...

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

node.js,express,redis

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...

How would you test this route code?

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...

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

javascript,node.js,express

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...

Express get error

node.js,model-view-controller,express

You need to initialize your app like this var app = require('express')(); ...

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

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) %> ...

404 on api authenticate for node restful

node.js,express,npm

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); ...

pass variables to jade template

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}....

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

node.js,express,body-parser

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...

sending multiple files down the pipe

node.js,express

There is no way to send multiple files like that in a single response, unless you use your own special formatting (standard multipart or otherwise) and then parse that on the client side (e.g. via XHR). Probably the easiest workaround would be to archive (zip, 7zip, tarball, etc.) the files...

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

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) {...

zip and download from nodejs

node.js,express,download

Try zip2.writeToResponse(res,'folder.zip'); instead of zip2.writeToFile('folder.zip');

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

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...

Redirect user to previous page after authentication

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; }); ...

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

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...

Passing a var from server to client

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...

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

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....

How to correctly use Express 4 multiple routers

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...

What is the bin folder in an express application for?

express

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 ...

Express - preventing two+ responses from being sent

node.js,express

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}); }); ...

Error handling when uploading file using multer with expressjs

node.js,express,multer,busboy

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....

pretty print json directly in page from Express

json,object,express

Depending on what you're going for using browser extensions or a program like Postman will make it easier for you to develop against.

Stream read returning empty in nodejs

node.js,express,node-webkit

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); });...

Why is address undefined in my app?

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); }); }); ...

Confused about nodejs (and the Passport middleware) sessions

node.js,express,passport.js

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...

error while using node proxy

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:...

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

node.js,express,passport.js

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)....

Set multer properties inside an express route

node.js,express,multer

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...

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

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 .... ...

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

node.js,express

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...

Node Server - Source Code accessible

node.js,express

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....

Node express 404 error HTTP status code

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({ ...

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

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....

Design pattern as alternative to front-end template locals

node.js,express,socket.io

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...

Accesing handlebars variable via javascript

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...

How to get ip in socket io

node.js,express,socket.io

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...

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

javascript,ajax,angularjs,express

In Angular this can be solved with an interceptor. See Angular-loading-bar as example.

Using middleware to call an Authentication API using ExpressJS

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,...

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

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...

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

node.js,express,socket.io

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...

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

node.js,express,download

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...

Select Mongoose Model Based on Express Route

express,routing,mongoose

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...

Full stack javascript routing explanation needed

javascript,node.js,express

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)....

Jade / Expressjs: Pass objects from server to client

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...

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

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...

How to use passport.js's TwitterStrategy sessionless?

node.js,express,passport.js

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. ...

Socket.io client does not connect to server

node.js,express,socket.io

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/EXPRESS/PASSPORT - Facebook App with Callback URL

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...

Send a POST when the user hits the bottom?

node.js,mongodb,express

"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...