Reputation: 99
I'm trying to make a post call via an html page. On 2nd application, i'm trying to access a cookie named cookie_test (can be set manually or via code in browser).
Under Application tab(Storage --> cookies), i'm able to see the cookie, but somehow i'm getting undefined in console log when trying to access it from 2nd application (refer 2nd code).
Application One (test.html is the only file in it & i'm trying to make a post call)
<form action="http://localhost:3000/page-two" method="POST">
<input type="submit" value="Go to P2">
</form>
Application Two (NodeJS/Express: index.js)
var express = require('express');
var router = express.Router();
router.post('/', function (req, res, next) {
console.log("COOKIE-TEST::::::", req.cookies.cookie_test)
res.render("page_two", { cookie_data: req.cookies.cookie_test });
});
module.exports = router;
Note: Within node application, cookies are accessible & works as expected. Issues seems to happen during redirection.
Upvotes: 1
Views: 1204
Reputation: 99
I was able to solve the issue by setting the cookie parameters as secure(true) & sameSite(none). Make sure to use latest version of express for sameSite property. This setting allowed my 2nd application to access it's cookies, irrespective of getting redirected from any source (in my case Application one).
Upvotes: 1
Reputation: 108839
A couple of things to check.
First, your nodejs app needs the cookie-parser
middleware if it is to receive any cookies from users' browsers. It looks like this.
var cookieParser = require('cookie-parser')
...
var express = require('express')
express.use(cookieParser())
...
You didn't mention how you set the cookie from your post route. You would do that like this with a call to res.cookie():
router.post('/', function (req, res, next) {
console.log("COOKIE-TEST::::::", req.cookies.cookie_test)
const testCookieVal = req.cookies.cookie_test || 'some default value'
res.cookie('cookie_test', testCookieVal)
res.render("page_two", { cookie_data: someCookieVal })
});
It's not clear how you set the cookie you're trying to retrieve in your post route. You should understand that your Application One html file is served from the file://
origin, and Application Two is served from the https://localhost:3000
origin. Browsers never send cookies associated with web pages served from one origin in requests to other origins.
Upvotes: 0