Pergunta

I'm using

app.use(require('./middleware/im')({
   maxAge: 30 * 1000,
   reapInterval: 20 * 1000,
   authentication: require('./libs/authentication/' + AUTH_LIBRARY)
}));

to authenticate the user(cookie based) in my node.js/express.js. Now my problem is I need my client side(a PHP + javascript) server send a cookie value to the node server via GET(jsonp) so I can authenticate the user. But If I do:

app.get('/cookie', function(){//set cookie here});

it won't work because the auth code in the middleware fires before they even call the action. What should I do so I can send a cookie(or any string) to the node.js server before the middleware fires? If that's not possible, is there any alternative way I can use so I can let the node.js server get the user's userid?

Thank you.

Foi útil?

Solução

To intercept the request, before your '.middleware/im' can get to it, you need to create your own middlware, which is surprisingly simple (the following goes before your call to app.use(require('./middleware/im')({ ...):

app.use(cookieDetect);
function cookieDetect (request, response, next) {
    if (request.url === "/cookie") {
        // do your stuff here
    } else {
        next(); // keep the middleware chain going
    }
}

Btw, as a JavaScript syntactical note, when you use function declarations (different than var myFunc = function () { ...), "scope hoisting" happens: that particular function declaration is available at the very beginning of that scope-level's execution, instead of from where it appears in the code. Which is why I'm able to app.use it before it appears in the code.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top