How to access the req object from an Actions2 function in SailsJS?

Viewed 574

I want to use my session information from a SailsJS standalone action ( from a controller I use req.session.<session variable name>)

But from a stand alone action ( Actions2 ) you don't define the functions with (req, res), but instead with (inputs, exits).

2 Answers

NeoNexus DeMortis Is correct, I just came across this and thought I could offer an alternative. Sails uses a module called machine-as-action that allows you to access the request object without passing env into the function. Without passing in env you can access req and res functions by calling this.req or this.res.

https://sailsjs.com/documentation/concepts/actions-and-controllers#actions2

Also, to my knowledge, the only reason to use res with actions2 is to set a custom response header (this.res.set('Name-Of-Header', 'whatever value you want for header'))-- or one of the convenience methods like this.res.type('image/png') which tells the user agent (e.g. browser) how to process the download. Same thing for whatever the method is to set the "content disposition" (which just means whether or not you want to instruct the browser to try to open it in-browser (which it might or might not do, depending on its capabilities) or always encourage it to skip even trying to open it at all and always just doing "save file as", even if it's something it could have opened itself, like a PDF)

Hello @Arturo welcome to SO!

This is a perplexing problem, as I can't remember now how I figured it out, because I can't seem to find documentation for this (I believe I went through the source code to find it). But, there is an "escape hatch" in Actions2 functions, a third parameter you can add, env. So, you have inputs, exits, env for your function signature; inside env is req and res.

Here is an example of using req to pass around session data: https://github.com/neonexus/sails-react-bootstrap-webpack/blob/release/api/controllers/admin/get-me.js

I'm using the isLoggedIn policy to populate the session in req, as I'm handling things a bit more manually, so I can use Sails' built-in models; seen here: https://github.com/neonexus/sails-react-bootstrap-webpack/blob/release/api/policies/isLoggedIn.js

Related