logo
down
shadow

How to register async middleware module within express.js app?


How to register async middleware module within express.js app?

By : drosell
Date : November 22 2020, 03:03 PM
this one helps. That module already provides an Express middleware, so it's as simple as:
code :
// ...
var myModule = require('./myModule');

myModule.init(function(err, acl) {
  if (err) throw err;

  // insert first `app.use()` here

  app.use(acl.middleware());

  // insert other middleware/route handlers here
});


Share : facebook icon twitter icon
Express middleware with async initialization

Express middleware with async initialization


By : Prashant Kanki
Date : March 29 2020, 07:55 AM
like below fixes the issue I'd recommend against such a singleton, dependency injection is a better solution here, and a connection per app is hardly scalable. A connection pool might be a better idea.
That said, you can do something like:
code :
var db = null; // to keep our instance
var asked = false; // to not make several requests that override each other
function openDb(db,ready){
    // if we already have it, we return the instance
    if(db !== null) ready(null,db);
    // if it was already asked by another instance, keep track of it
    // to avoid multiple requests.         
    if(asked) asked.push(ready);
    asked = [];
    openDbCode(db,function(err,result){
        if(err) {
           ready(err,null); // error case
           asked.forEach(function(fn){ fn(err,null); }); // notify waiters of failure
        }
        db = result; // save the reference
        asked.forEach(function(fn){ fn(db,null); }); // notify all waiters
    })
}
module.exports = function(db) {
    return function(req, res, next) {
       openDb(db,function(err,db){
           if(err) handleDbOpenErrorLogicHere();
           // middleware stuff, same db available here, call next to continue
        });
    };
}
Unable to register Express middleware

Unable to register Express middleware


By : user3691493
Date : March 29 2020, 07:55 AM
wish help you to fix your issue 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 requiring authentication (and subsequent authorization). , When you register the route with
code :
router.get(
    '/protected/:id',
    authorize(['ADMINISTRATOR', 'MANAGER', 'OWNER']),
    controllers.protected.retrieve
)
function authorize(req, res, next) {
    ...
};
router.get('/protected/:id', authorize, ...);
// a factory function to create authorization middleware functions for given roles
function authorize(roles) {
    // create and return an actual authorization middleware function
    // to handle requests using the roles given when created
    return function(req, res, next) {
        if(_.contains(roles, req.user.role)){
            req.authorized = true;
            return next();
        }
        return next(new Error("Unauthorized"));
    }
}

router.get(
    '/protected/:id',
    authorize(['ADMINISTRATOR', 'MANAGER', 'OWNER']),
    controllers.protected.retrieve
)
Async Express middleware, how does it know

Async Express middleware, how does it know


By : Tom
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further So I have my Express (4.0) configuration: , You can do res.json() only once. Consider this example:
code :
var express = require('express');
var app = express();

app.get('/json1', function (req, res) {
  setTimeout(function () {
    res.json({ok:true});
  }, 2000);
});

app.get('/json2', function (req, res) {
  setTimeout(function () {
    res.json({ok:true});
    res.json({ok:true});
  }, 2000);
});

app.listen(3333);
$ curl http://localhost:3333/json1
{"ok":true}
curl http://localhost:3333/json2
{"ok":true}
_http_outgoing.js:344
    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
app.get('/send1', function (req, res) {
  setTimeout(function () {
    res.send('ok');
  }, 2000);
});

app.get('/send2', function (req, res) {
  setTimeout(function () {
    res.send('ok');
    res.send('ok');
  }, 2000);
});
app.get('/end1', function (req, res) {
  setTimeout(function () {
    res.end('ok');
  }, 2000);
});

app.get('/end2', function (req, res) {
  setTimeout(function () {
    res.end('ok');
    res.end('ok');
  }, 2000);
});
app.get('/end1', function (req, res) {
  setTimeout(function () {
    res.end('ok');
  }, 2000);
});

app.get('/end2', function (req, res) {
  setTimeout(function () {
    res.end('ok');
    res.end('ok');
  }, 2000);
});
app.get('/write1', function (req, res) {
  setTimeout(function () {
    res.write('ok\n');
  }, 2000);
});

app.get('/write2', function (req, res) {
  setTimeout(function () {
    res.write('ok\n');
    res.write('ok\n');
  }, 2000);
});
app.get('/empty', function (req, res) {
});
Async await in Express middleware not working

Async await in Express middleware not working


By : JORGE
Date : March 29 2020, 07:55 AM
this will help It looks like convertExcel is not a Promise-returning function, but rather uses an old-school callback. await does not work with those, so it's instead awaiting Promise.resolve(undefined) since the function returns undefined, not a Promise. Thankfully, in Node 8 and later, there's a promisify utility to convert callback-style functions to Promise-returning functions so that await can be used.
code :
const { promisify } = require('util');
const convertExcel = promisify(require('excel-as-json').processFile);

// ...

const guestData = await convertExcel(req.file.path, null, null);
req.guestlist = guestData.map((guestObj) => Object.values(guestObj)[0]);
Handling errors in express async middleware

Handling errors in express async middleware


By : user1494995
Date : March 29 2020, 07:55 AM
it helps some times
The problem is that when it rejects, it doesn't go to my error middleware, but if I remove the async keyword and throw inside a middleware it does.
code :
Layer.prototype.handle_request = function handle(req, res, next) {
  var fn = this.handle;

  if (fn.length > 3) {
    // not a standard request handler
    return next();
  }

  try {
    fn(req, res, next);
  } catch (err) {
    next(err);
  }
};
app.get('/route', async(req, res, next) => {
    try {
        const result = await request('http://example.com');
        res.end(result);
    } catch(err) {
        next(err);
    }
});
const asyncHandler = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

module.exports = asyncHandler;
app.use(asyncHandler(async(req, res, next) => {
    await authenticate(req);
    next();
}));

app.get('/async', asyncHandler(async(req, res) => {
    const result = await request('http://example.com');
    res.end(result);
}));

// Any rejection will go to the error handler
Related Posts Related Posts :
  • clearvalidators not working in angular 6 form control
  • Remove Count Attribute in json data
  • queue up function callbacks
  • How to stop all Soundcloud streams in once?
  • Sliding div onclick left/right
  • RequireJS JQuery shim doesnt work with VS2013
  • What is the Meteor concurrency model?
  • Events on children of contenteditable element
  • Simple jquery not working to print the input value
  • Javascript templating language in reverse
  • Making Pagination in Javascript Scalable (for large # of db results)
  • Performance of Stateless Authentication in SPA and SSO (Single Sign On)
  • Assigning a value for view asynchronously
  • Mocha JS: How to reuse assertions within a spec?
  • Is ember.js stable enough to use in a real world project?
  • jQuery Load() not loading within div
  • encode stream from webCam h264
  • Regex to find pattern, return subpattern
  • Why does this regex to remove empty <p></p> tags from a string fail?
  • Rails: pass data to javascript
  • Quickest way to check if a number is in a set?
  • Phonegap events online/offline not working
  • In HTML5, please explain the meaning of '?' in the statement
  • Form to use AJAX rather than a page refresh but also utilise error handling?
  • JQuery Script looping error
  • different size divs align top left
  • Image fade-in when webpage finishes loading
  • Seeking HTML5 audio element causes delay (breaks sync)
  • How can I read & write data to a new tab in Firefox?
  • jQuery or JS turn all words into italic type
  • iOS css -webkit-transform: scale doesn't offset touch events
  • Populate select list using javascript
  • Can you work out why my .js file doesn't seem to be linking to my html?
  • Make slideToggle effect only one element at a time
  • Output sound using JavaScript
  • What is the analytics.js equivalent of _trackPageview found in ga.js
  • How can I check if a JS file has been included already?
  • hasClass and condition not working
  • EDITED: I'm having issues with a button and its function
  • Importing XML in HTML with javascript
  • Create new function in contentScriptFile in Firefox extension
  • Should I build Node.js from source or download the OS X installer?
  • How to enforce integer sizes in JS? (TypeScript?)
  • How to update the JSON object without deleting old values using javascript
  • Reading a javascript variable containing a string into another file
  • Possible to prevent 403 errors from logging to the web console?
  • Jquery Accordion - Expand and collapse div on hover
  • jquery .hide() function - Hide mobile, Display Desktop
  • Holding password in javascript variable - security implications?
  • JQPlot trouble to render vertical stacked bar and horizontal legend
  • counts days inbetween then add class to those days with nested divs?
  • Marionette.js with Rails (Devise) Authentication
  • javascript anonymous function evaluation idiom
  • Why am I losing the decimal when working this equation in Javascript?
  • Site redirects to index.php after being open while making calls to an API using AJAX
  • How to determine when multiple callbacks are all done
  • How to update Yeoman dependencies?
  • How can I do a /resolve with the Soundcloud Javascript SDK?
  • I'm not able to call a named callback function
  • How to get value of Paragraph element contained in <div> in HTML using JavaScript
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org