I am trying to create an application that can post data both through ajax and through traditional form requests. I am surprised by the lack of information I am finding online about the topic. I guess these days we all assume we have access to client side JS?
I went with express-session, but am getting frustrated at how hard it is to determine what's actually happening. From what I can understand it's cacheing cookie data on the client and somehow including those in requests automatically? Then is it safe to assume that this format will NOT work without client-side javascript support?
Given a form like this:
<form method="post" action="/create">
<input name="value1" onChange={this.handleInput} value={this.state.value1} />
<button onClick={this.submitForm}
</form>
My requests sent via ajax will pass auth (due to having session data):
event.preventDefault();
postUrl(`/create`, {value1: this.state.value1})
.then(jsonRes => {
// works
});
being picked up by auth middleware which uses express session and passport:
module.exports.secured = (loginUrl = "/employers") => {
return (req, res, next) => {
if ( (req.isAuthenticated()) ) { return next(); }
req.session.returnTo = req.originalUrl;
res.redirect(loginUrl);
return next();
};
};
which protect a pretty simple api route for creating:
router.post('/create', secured(), (req, res) => {
My thinking is that even if JS is enabled, I could handle the request at this route, but the problem is with authenticating.
What can I do to get my session data sent over in these 'non-js' requests?
I remember in traditional webstacks like Rails or PHP some sort of token is rendered into the form in a hidden field or in the action on render. If this would work, does anyone know how to get the 'vital data' so to speak out of the express session to send as the token? Not possible?
Looking in req.cookies or req.session of the req object that gets parsed in the serverside render, I do not see anything that would be useful for this.
Set-Cookieheader and that cookie will be attached to every request sent afterwards so that the server knows who you are. Could you please explain your question in more detail?