FAQ Database Discussion Community


Unable to register Express middleware

node.js,express,middleware
I'm trying to write a very basic piece of middleware for Express that checks to see if a user has some specified role required to access a resource. I have another piece of middleware that comes before this, which adds a user object to the request req for every route...

properly call EF SaveChanges after each request with Autofac managing scope

entity-framework,owin,autofac,middleware
I would like to put in a bit of infrastructure on my project to SaveChanges on my db context at the end of every request. So I create a simple piece of Owin middleware app.Use(async (ctx, req) => { await req(); var db = DependencyResolver.Current.GetService<MyDbContext>(); await db.SaveChangesAsync(); }); This does...

Modifying request object in middlewares-Node.JS

javascript,node.js,express,middleware
I have a bunch of middlewares in my Node.JS application, is there any way to delete/modify req.path and be reflected in the next middlewares? Please let me know if you need more clarification if my question is vague? UPDATED: even req.path = 'foo' is not changing my req.path after that...

Express user authentication middleware, how much should it do?

javascript,express,middleware
I'm trying to learn Express session and authentication handling. For example: app.post('/login', authCredentials, function(req, res) { console.log("second") }); function authCredentials(req, res, next) { //this happens first console.log(req.body) // => { username: etc, password: etc } next(); } My question is just how much should my authCredentials function do? For example...

Why are Distributed Systems considered complex?

asynchronous,distributed-computing,middleware
I'm just getting into the concept of a Distributed System and its advantages and disadvantages. In the book I'm reading it discusses the complexity of a Distributed System and that they are inherently complex, it lists the following as potential reasons for complexity; Heterogeneity Asynchronous communication Partial failures What I...

Stylus global variables

angularjs,global-variables,middleware,stylus,file-structure
I have a core.styl where I put my grid-style, some stylus-functions and some variables. This file should be imported in all of my routes. Beside that I have an page.styl which dependes on my current route (e.g. contact.styl for /contact) Note: My project is based on angular.js so the html-head...

Mongoose find and findOne middleware not working

node.js,mongoose,find,middleware
If have the following schema and middleware hooks, but the find and findOne hooks are never being called. The save and update hooks work as expected. According to the Mongoose Middleware documentation, this should be available. // define the schema for our recs model var recSchema = mongoose.Schema({ dis: String,...

In express when i call next(err) the next tick/middleware does not get called/processed

node.js,express,error-handling,routing,middleware
This is a cool little middleware that returns a 405 error if the req.url matches one of the other routes connected to the same router object. If it finds a match it will check to see if there is a matching http verb if there is no matching http verb...

Middleware in ExpressJS app uses next() to call itself

node.js,express,middleware
I have a basic ExpressJS server that's simply meant to log a connection's IP, and serve static we pages. What happens when I connect to it myself is that the middleware that logs the request's IP repeats itself multiple times. If I remove the call to next() this stops, but...

Express middleware and parameter handling ordering on route

node.js,express,middleware
So I am running some API tests and I noticed that one test is failing because it is running some parameter handling logic before middleware, now here is an example of the route definition: app.post("/something/:some_param", middlewareA, middlewareB, middlewareC, function(req, res) { // Do stuff }); Now I assumed (wrongly I...

How to properly apply routes inside another file

javascript,node.js,express,routes,middleware
I'm fairly new to express js and I want to know how to use router. I created a file named categories.js inside routes directory with this code. categories.js code: var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/categories', function(req, res) { res.send('this is the category');...

get the url in the middleware laravel

url,laravel,middleware
I have my middleware and inside it I am trying to reach the current url of the page. so I did something like that: $url = Request::url(); and I used: use App\Http\Requests; use Illuminate\Http\Request; but I keep getting the following error: Non-static method Illuminate\Http\Request::url() should not be called statically, assuming...

Middleware redirect with value

php,http,laravel-5,middleware
I'm building project on laravel 5 and at the moment I'm bit confused. I check if user is loggedin in my middleware. It he is not, I want to generate a link, specially for unique user like this: $code = str_random(32); return redirect()->guest('user/review/information', [$code]); I'm getting error: The HTTP status...

Laravel 5 redirect to previous root after filters

laravel,redirect,laravel-5,response,middleware
I ran into simple problem but I still can't solve it. At the moment i got middleware which checks user status, if it's 0 middleware redirects user to choose status root. So how do i redirect user to route, after successfully picking status, where he got cought by middleware? My...

Rendering an “internal” Rails controller from a middleware

ruby-on-rails,rack,middleware,actionpack
I have a Rails middleware stack, and I have a piece of MW outside ActionDispatch. Ideally I would like to render a page using ActionDispatch by triggering a URL which is internal (not accessible via usual URL routes) - similar to the way Devise renders it's "auth failed" pages. The...

Should the response argument to `process_response` always be a subclass of HttpResponse?

django,middleware
Question is in the title. Found that when our views raise Http404 exception, the response argument to our process_response methods is an exception instead of an HttpResponse. Is this correct? Do we need to account for such cases when writing middleware or is something misconfigured?...

Should I implement user data sanitization/validation as middleware?

php,validation,middleware,slim,sanitization
I'm reimplementing my user management system with Slim, and I'm trying to figure out where I should do user data sanitization/validation. I've been reading about middleware, and I'm wondering if this is an appropriate way to implement data validation. My plan for validation is to use a validation schema (a...

'auth' Middleware with Route::resource

authentication,laravel,laravel-4,middleware
How can I use middleware with resources? Route::resource('myitem', ['middleware' => 'auth', 'uses' => 'App\\Controllers\\MyitemsController']); Just followed https://laracasts.com/discuss/channels/general-discussion/struggling-with-routeresource-and-auth-middleware but unfortunately could not solve. Getting error: ErrorException (E_UNKNOWN) Array to string conversion Open: /vendor/laravel/framework/src/Illuminate/Routing/Router.php protected function getResourceAction($resource, $controller, $method, $options) { $name =...

Using middleware to add arguments to view functions in django

python,django,views,middleware
I have a pretty small, basic site with a handful of views. Pretty much all of the views perform some interaction with an external API. In each view I instantiate an object of my API class, which obviously is not very DRY. I also have a piece of middleware that...

OWIN OpenIdConnect middleware - set RedirectUri dynamically

owin,middleware,openid-connect
Is there any way how can I set RedirectUri property for OpenIdConnectMessage based on a Request scope, not Application scope? My app is serving multiple domains (myapp.com, myapp.fr, ..) and based on domain, it determine default language for the content. I need that the user is taken back to the...

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?

How can I inspect the set of Express.js middleware that is being used?

node.js,debugging,express,middleware
Backstory: I'm trying to debug an issue in one piece of middleware that I think is coming from other piece. But, I'm not sure. So anyway, I would like to be able to check what middleware is actually being called, because I'm not sure of the ordering. Is it possible...

Laravel 5 redirect loop error

php,redirect,laravel-5,infinite-loop,middleware
I trying to make a login and admin script, the problem is that I have a redirect loop I dont know why. I want the login users and can be in the / path not /home. If change return new RedirectResponse(url('/')); to return new RedirectResponse(url('/anotherpage')); it works but I want...

Route-specific Middlewares with Negroni

web,go,middleware
I have a web server using httprouter and negroni. Users log into this system through external OAuth. We save the token to the encrypted session which indicates whether or not they are logged in. I would like to use a middleware to verify whether or not this token exists, and...

How to respond in Middleware Slim PHP Framework

php,rest,authentication,middleware,slim
I am creating middleware for auth into REST API. My API is created using Slim PHP Framework ,which in case provide great features to build APIs. One of this feature is Middleware. I need to check credentials in Middleware and respond with an error (HTTP code with JSON descriptions) to...

Send production errors to slack instead of email

django,reporting,middleware,slack-api
I wanted to make my Django app send debugging information to slack instead of by email, which is the default. Disabling email is simple. Just don't put any emails in ADMINS setting Sending information to slack is easy. Just add an incoming webhook Now, where should i create the logic...

Customizing auth middleware - Laravel 5

php,authentication,laravel,middleware
The delivered auth middleware that comes with Laravel 5 is great for user-only routes and controllers, however I want to add the ability to also check if the user is an administrator. Currently, in my controllers, I have this for every class: if (Auth::user()->level <= 1) { // admin can...

Is Django has something like “database middleware”?

python,django,database,middleware,django-middleware
Django has middleware to achieve do somthing when request and response. Is Django has "database middleware" to achieve do somthing when write data and read data. For example,some old database does not support to utf8mb4 , so it can't support all of emoji. If Django has "database middleware" I will...

Breaking down the ring middleware scenario

clojure,middleware,ring
Ring is super sleek and has some pretty sensible defaults for middleware(s). When I made a new app through leiningen (lein) I ended up with something like this in my router/handler (def app (wrap-defaults app-routes site-defaults)) https://github.com/ring-clojure/ring-defaults Now I want to add more middleware (cemerick/friend) so I can do things...

meteor iron-router and getting the names of all routes for the accounts-entry package

meteor,routing,iron-router,middleware
The popular accounts-entry package has an iron-router related bug in it. I believe the later versions of iron-router changed to work better as middleware and so a call to Router.routes At line 87 of this file the following code is used: _.each Router.routes, (route)-> exclusions.push route.name # Change the fromWhere...

How can I use body-parser with LoopBack?

node.js,express,middleware,loopbackjs,body-parser
I see that LoopBack has the Express 3.x middleware built-in. Indeed, body-parser is in loopback/node_modules. But I cannot figure out how to use it as middleware. I have never worked with Express 3.x, so maybe it's just that. require does not work, obviously, unless I install body-parser as a dependency...

Laravel 5 - Defining middleware for multiple routes in controller file

php,laravel,controller,views,middleware
Stackers! I'm currently learning laravel5 and I love it, but I'm struggling with one thing. Since Laravel 5 we have Middleware which we can use in controller's construct function, like this: Controller file: public function __construct() { $this->middleware('admin', ['only' => 'create']); } Now what I want is to define HERE^...

Parsing Post Form Data Node.js Express

node.js,forms,parsing,express,middleware
I am getting form data in this form '------WebKitFormBoundarysw7YYuBGKjAewMhe\r\nContent-Disposition: form-data; name': '"a"\r\n\r\nb\r\n------WebKitFormBoundarysw7YYuBGKjAewMhe--\r\n I'm trying to find a middleware that will allow me to access the form data like: req.body.a // -> 'b' I've tried var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({...

Sending messages to MQOutput node

message-queue,websphere-mq,middleware,messagebroker,mqueue
Just want to confirm the correct way the MQ delivers messages to the MQOutput node. Recently came across a situation where i a felt bit confused. Here is the scenario. I have a local queue on Qmgr,say(A) which receives messages from applications and have a local broker associated with this...

Sails.js route redirect with a custom policy

node.js,sails.js,middleware
Situation I want to achieve: Request to /register runs AuthController.register Request to /facebook runs AuthController.register but applies a facebook policy before. I have created a policy in /api/policies/facebook.js like this var graph = require('fbgraph'); module.exports = function(req, res, next) { facebook_token = req.query.facebook_token; if(!facebook_token){ res.send('401',{error:"Missing facebook token"}); } graph.setAccessToken(facebook_token); graph.get("me",function(err,graph_res){...

What is the difference between get/post/… and use

express,middleware
All: I am new to Express 4 router. When I tried some login/signup example, I got one question about the .use and .get/.post function: I saw sometimes it uses: var express = require('express'); var router = express.Router(); router.get('/hello', function(req, res, next) { res.send("Welcome"); }); and in main app, we use...

Laravel 5 - Middleware get user ID and send to controllers

laravel,laravel-5,middleware
Hello guys ! I'm working on an API that has a middleware authenticating the user with a unique ID. After making sure that this user exists, I want to send his database ID to the controller coming next, whichever it is. Is that a good idea ? Or should I...

What is the correct way to “hook” into app.response functions in express?

node.js,express,middleware
I need to way to add some data to app.json and app.jsonp responses in express after app.json is called, what is the correct way to add middleware to this? I know I could probably do something like: var jsonTemp = function(status, data) { if (!data) { data = status; status...

How can I store request-local information in Yesod middleware and retrieve it from a Handler?

yesod,middleware
Before any handler code is executed, I need to load some information about the user, which is determined by the request cookies, and then access that in all of my handler code. I've looked at the yesod-core codebase and found that I could override the yesodMiddleware function and provide a...

Golang go-workers custom logging middleware?

logging,go,sidekiq,middleware
I'm building a Golang app that implements a Sidekiq-compatible jrallison/go-workers work queue and a custom logging wrapper around Sirupsen/logrus for marshaled JSON logs. Now, all of my app (except for go-workers so far) uses my logger-wrapper in a central place to ensure that 100% of its output is JSON compatible....

Slim PHP Framework middleware custom URL filter

php,rest,authentication,middleware,slim
I am creating API using Slim Framework. I need to filter requests required authentication and route them to the specific auth handler. Or it would be better to say that I need to filter URI that don't require auth (public information). I have created following middleware skileton class TokenAuth extends...

Laravel 5 Function () not found

php,laravel,middleware,laravel-routing,laravel-5
I'm putting together a site which has a protected section where users must be logged in to access. I've done this in Laravel 4 without too much incident. However, for the life of me I cannot figure out why I can't get it to work in Laravel 5(L5). In L5...

Who provides the next() function in Express middleware?

javascript,node.js,express,middleware
I'm confused about how next() works in Node.js and Express middleware. There have been some other questions about middleware works, for example here, but I'm looking for a different answer. The main question bugging me is, who is providing the next() function? For example, in my standard generated express app,...

Laravel 5.0 custom 404 does not use middleware

laravel,http-status-code-404,middleware
I'm using a middleware to parse the output of the templates. This is working fine for all pages. However when I want to show a 404 (got a custom page for that) it doesn't treat it as a http request (that's what I think) since it doesn't go through the...

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

Handling errors in an express middleware module

node.js,express,middleware
I'm creating a module, which is an express middleware. My question is, when it encounters some kind of error (for example an acl module that sees that the user has no access right to this content), what is the best practice, calling next() with an error, so the app using...

Setting up three expresss instances: admin, site and app

javascript,node.js,express,middleware,ghost-blog
Friends, I consider myself a javascript programmer at an intermediate level, but these questions will sound amateur, forgive me. I was doing reverse engineer in the Ghost.org blog plataform (CMS).. trying to understand how they did it, and I found that they have three instances of express(): parentApp, blogApp and...

Enabling Middleware in Lumen (Laravel)

php,session,laravel,middleware,lumen
I've been trying out Lumen (a micro PHP Framework based on Laravel 5) for a few hours and I'm not able to add Middlewares to my project which basically means that I'm not able to use Features like Sessions or CSRF Protection. My .env looks like this: APP_ENV=local APP_DEBUG=true APP_KEY=some32charslongkey...

NodeJS Express Module: 'dotfile' options no working

node.js,express,middleware,dotfiles
I am running into an oddity when using express.static() to serve static resources. Specifically the dotfiles object of the options argument is not producing the expected behavior. Within the express documentation it states : ...express.static is based on serve-static, and is responsible for serving the static assets... Furthermore it claims...