'not able to set the cookie from script tag javascript nodejs
On the Html Side
<script src="http://localhost:3002/widget-load?clientId=1" type="text/javascript">
And on the nodejs
app.get('/widget-load', function (req, res) {
const { clientId } = req.query;
// Try 1
res.cookie("clientId", clientId, {
// httpOnly: true
});
// Try 2
res.setHeader('Set-Cookie', `clientId=${clientId};`);
res.sendFile(__dirname + '/public/static/js/widget-load.js');
});
but this is not working. Even I tried
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
});
even i am using cookie-parser
var cookieParser = require('cookie-parser');
app.use(cookieParser());
but still this is not working. No cookie is getting set on browser
Solution 1:[1]
With a combination from the answer in my link, and your requierments, it is working here, cookie is set to clientId=1
. For cross site resources you have to set the options to sameSite: 'none'
and secure: 'false'
if you are not running ssl
.
const cookieParser = require('cookie-parser');
const express = require('express')
const app = express()
app.use(cookieParser());
app.get('/widget-load', function (req, res) {
const { clientId } = req.query;
var cookie = req.cookies.clientId;
if (cookie === undefined) {
res.cookie('clientId',clientId, {httpOnly: true, sameSite: 'none', secure: 'false' });
console.log('cookie created successfully');
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
// // Try 1
// res.cookie("clientId", clientId, {
// // httpOnly: true
// });
// // Try 2
// res.setHeader('Set-Cookie', `clientId=${clientId};`);
res.sendFile('widget-load.js',{'root':'public'});
});
app.listen(3002, () => {
console.log(`Example app listening on port 3000`)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |