So I have a route in my Express app with two middleware in them:
app.foo('/thisRoute', fancyMiddleware.one, fancyMiddleware.two);
Both middlwares function in order just fine. However, in fancyMiddleware.one I have this:
var one = function(req, res, next) {
...
...
res.cookie('myCookie', data, {maxAge: 3600000});
console.log(req.cookies.myCookie)
return next();
}
To test everything I'm using PostMan to test all my requests.
The logged output for req.cookies.myCookie always returns undefined. But in the Body tab I can see that the cookie is present.
If I log out the same cookie in fancyMiddleware.two its also undefined.
why is this returning undefined?
EDIT: So, with a few answers of "why" being given, I now realize I should have also asked:
How do I read the cookie I just set?
I dont really need it right after I set it in fancyMiddleware.one, but I do need it in fancyMiddleware.two
EDIT 2: I forgot to mention I'm working with an Express 3 setup. Probably relevant.
The req.cookies is populated only once, when the cookie parser middleware is executed.
res.cookie() immediately sets the Set-Cookie header, so you'll have to use res.get('Set-Cookie') to see the current values.
You are setting the cookie on the response-object res, but you are asking it from the request req.
Related
I wish to know how can I have both get and post request handled by app.use the way I do it using app.route
app.use('/', (req, res, next) => {
if (isLaunched) {
return next()
}
// You can also render if you want
res.render('coming-soon')
});
How can I handle a post request to this?
According to https://expressjs.com/en/guide/using-middleware.html the syntax you already have is used for any type of HTTP request - including GET and POST. You can detect the method via req.method.
app.use() already handles ALL http methods, including GET and POST. You can see exactly which method it is for any given request by checking req.method.
If you had trouble with some GET or POST when doing this, then please show the specific code and the specific request that it didn't work for. If you didn't try it yet, then just try it as it should work just fine.
Middlewares are mounted using app.use(<middleware-name>) so, you can add it to all routes like you do for bodyParser/CORS etc.
If you want to mount for specific routes you can use
app.post("/example" , middleware, (req,res)=>{
res.send("Hello world")
})
Refer to Use middleware on specific routes
So I've been working on this React/Node application since August now. Never encountered such issue. Been trying to fix, but it just wouldn't happen.
So React is sending an Axios request to Express, and in the first middleware Tier req.body is empty. I tried to change headers back and forth. So changing them to urlencoded actually turns the req.body into this {'entire stringified payload':''} so as if it's an object with a stringified JSON payload as the property name. Setting the headers as application/json doesn't do anything.
(async function(x) {
await Axios.post(`https://${x}/dispositionController/executeDisposition`,payload)
})(this.props.correctEndpoint)
This is the piece of code that is sending data to Express. I didn't want to make it an IIFE, I tried many things, and made it an IIFE out of desperation. This is middleware tier in Express where req.body is empty it is actuall the first middleware tier after error-handling middleware tier for http.
dispositionController.use((req,res,next)=>{
console.trace(req.body,'req.body here');
console.trace(req.body.Note,'req.body.Note');
throw new Error('');
global.thisSocket.to(`${req.body.dispoSocketID}`).emit('postingDispo');
req.body.Note=req.body.Note.replace(/[^A-Za-z]/g,"");
switch(req.body.eventID) {
case 5:
req.body.typeOfRegular='Inbound';
break;
case !5:
req.body.typeOfRegular='Outbound';
break;
}
next();
})
Please help.
I will demonstrate my problem with this simplified code:
app.get('/test', (req, res) => {
let x = req.query.someVar;
app.post('/test', (req, res) => {
console.log(x);
});
res.send(`Hello ${req.query.someVar}`);
});
The first time this code runs, the POST callback function saves a reference to x which is whatever I pass as query parameters. if I change the query parameters, send another GET request it will be updated in the server's response i.e.res.send(Hello ${req.query.someVar}); but a POST request will still log the original x value to the console.
Why is it behaving this way? I have tried many things like passing by objects and through other functions, etc..
I am familiar with how closures work, but obviously not entirely as this is most definitely a problem with the POST call back preserving the value of the query parameters and not updating them.
Thanks.
I'm not sure what you are trying to do. No one defines a POST inside of a GET, they do that at the root level, unless you want the GET request to change the behavior of your server. app.post means 'add a new route to handle a POST'. Perhaps you wanted to actually send an HTTP request from the GET handler?
If you want the behavior to change maybe just handle the POST at the root level and set a global flag in the GET handler to indicate that POST should do something different with subsequent requests.
I'm currently getting started with Sails.js, and I want to add user accounts to my toy app, so I installed the "sails-auth" package that creates a Passport-based user authentication system. I can create new users by sending POST /user, and I can sign in with POST /auth/local.
The documentation says:
Authenticate with the local strategy via a POST to /auth/local with params identifier (email) and password). This will also create a session. See passport.local for more.
However, when I try to GET /user/me, which routes to a controller action that should return the current user in the session, the page instead gives an empty response. Why is this happening? Is there some kind of configuration step that I'm missing?
By the way, I haven't changed or messed around with the sails-auth package. It's still completely new; the "me" action looks like this:
me: function (req, res) {
res.ok(req.user);
}
EDIT: I've found a temporary workaround by searching the issues in the sails-auth repo. Instead of getting a user object from req.user, you can get a string user ID from req.session.passport.user.
Your me action as written is only going to return whatever you are passing in as the user param. Sails builds on top of Express.js so req is the request from the browser and res is the response to the browser.
Most likely you are sending the data to your me action in the req body which is why your response is blank, simply put, req.user is empty so the response is empty. In that case you would access it with req.body.user, you could also try var user = req.params();
For debugging and just generally getting a feel for how the req and res objects are structured I suggest you always start sails (in development, never in production) with the verbose flag.
sails lift --verbose
Then you can do this:
me: function(req, res){
sails.log.verbose(req);
res.ok(req.user);
}
And have it print out the entire req object so you know what's in req.user.
Typically though you would do a database lookup as the user param would be an id. Which means your me function might look (something, obviously depending on your dbc it might be pretty different) like:
me: function(req, res){
var userId = req.body.user;
User.find({'user_id': userId}.exec(function(err, user){
if(err){
//tell peeps there was an error
}else{
res.ok(user);
}
});
}
Best debugging for routes and for the request object:
'/*' : function(req, res, next) {
sails.log.verbose("method: ", req.method, "\n body: ", req.body, "\n url:", req.url);
next();
},
Just paste that at the start of your routes module.
so I basically want to use sessions to store the users name and check to see if the user logged in or not. If not, the page will redirect to the login page.
I am using Node.js,express,and couchDB.
Here is how i set up my session so far
var MemoryStore = require('connect').session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({
secret: "keyboard cat",
store: new MemoryStore({
reapInterval: 60000 * 10
})
}));
To store something in the session, i use the following code right?
req.session = {user:name);
So the session variable seems to work on my login page. I successfully store the user's name into the session However, when I try to access the session variable on another page, it gives me the error
Cannot read property 'user' of undefined
all i'm doing is:
if (req.session.user){
Why is this error happening? are sessions not global to the whole app? Or am I missing something entirely here.
Thanks in advance!
If you're doing app.use(app.router) before the lines that set up the cookie and session handling, try moving it to after them. That fixed the same problem for me.
I was trying to solve the exact same problem for he last few hour.
Try initializing your server like that:
var app = express.createServer(
express.cookieParser(),
express.session({ secret: "crazysecretstuff"})
);
That should work.
I had same issue of getting undefined for session variable which I knew was set ok.
In my case it turned out to be caused by cross origin request, I had forgotten the withCredentials header on the request.
So for example in my client side Angular app I needed to do this:
var config = { withCredentials: true };
return $http.get(appConfig.apiUrl + '/orders', config);
and in Express this:
res.header('Access-Control-Allow-Credentials', true);
the sessionSecret in the configuration (config.json?) should be non-empty:
sessionSecret: "something other than an empty string",