简体   繁体   English

无法从脚本标签 javascript nodejs 设置 cookie

[英]not able to set the cookie from script tag javascript nodejs

On the Html Side在 Html 侧

<script src="http://localhost:3002/widget-load?clientId=1" type="text/javascript">

And on the nodejsnodejs

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即使我正在使用cookie-parser

var cookieParser = require('cookie-parser');
app.use(cookieParser());

but still this is not working.但这仍然行不通。 No cookie is getting set on browser浏览器上没有设置 cookie

With a combination from the answer in my link, and your requierments, it is working here, cookie is set to clientId=1结合我链接中的答案和您的要求,它在这里工作,cookie设置为clientId=1

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.cookieName;
    if (cookie === undefined) {
      res.cookie('clientId',clientId, {httpOnly: true });
      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 3002`)
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM