在 node.js 脚本中创建一个 cookie

Create a cookie in a node.js script

我正在尝试 node.js 脚本。我尝试使用 express/cookie 解析器,但不使用 ... ATM 我在本地模式下工作,但我会在网络服务器上使用它。

在我所有的尝试中,我遇到了任何错误,但 cookie 没有。

我最后一次尝试(没有 express/cookie 解析器):

const http = require('http');
const fs = require('fs');
const port = 53134;
const url = require('url');
const fetch = require('node-fetch');   
let express = require('express'); 
let app = express();
let cookieParser = require('cookie-parser');
app.use(cookieParser());



http.createServer((req, res) => {
let responseCode = 404;
let content = '404 Error';
const urlObj = url.parse(req.url, true);
let isEclaire = false;

if (urlObj.query.code) {
    const accessCode = urlObj.query.code;
    console.log(`The access code is: ${accessCode}`);
    
    const data = {
        client_id: '805884181811822624',
        client_secret: 'JRSPE0nmRn881Mi9cLC-gMozHKWLQVPT',
        grant_type: 'authorization_code',
        redirect_uri: 'http://localhost:53134',
        code: accessCode,
        scope: 'identify guilds',
    };

    fetch('https://discord.com/api/oauth2/token', {
        method: 'POST',
        body: new URLSearchParams(data),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
    })
        .then(discordRes => discordRes.json())
        .then(info => {
            console.log(info);
            return info;
        })
        .then(info => fetch('https://discord.com/api/users/@me', {
            headers: {
                authorization: `${info.token_type} ${info.access_token}`,
            },
        }))
        .then(userRes => userRes.json().then(userData => {
            console.log(userData);
            fetch(`https://discord.com/api/guilds/799385448824438824/members/${userData.id}`, {
                headers: {
                    authorization: `Bot ODA1ODg0MTgxODExODIyNjI0.YBhYIQ.h4zLzR7ybBC1uvFSb4iZTH-JVhM`,
                },
            })
            .then(guildRes => guildRes.json().then(guildData => {
                console.log(guildData)
                for(let i = 0; i<guildData.roles.length; i++){
                        console.log(guildData.roles[i]);
                     if(guildData.roles[i] = '804827924217593896') isEclaire = true;
                    }
                console.log(isEclaire)
                    if (isEclaire == true) {
                        console.log('condition is true'); 
                        // Write auth cookie WP
                        res.writeHead(200, {'Set-Cookie': 'cookie', 'Content-Type': 'text/plain'});
                        res.writeHead(301, {Location: `http://localhost:53134/?code=${accessCode}`});
                        res.end();
                    } else {
                        console.log('condition is not true');  
                    }// Console will output 'condition not is true'
            }
            ))
        }))
        }

if (urlObj.pathname === '/') {
    responseCode = 200;
    content = fs.readFileSync('./index.html');
}

res.writeHead(responseCode, {
    'content-type': 'text/html;charset=utf-8',
});

res.write(content);
res.end();
})
    .listen(port);

    

我对是否使用 express/cookie 解析器有任何偏好。

谢谢你的想法

你的服务器请求处理程序的编写方式,它总是这样调用:

    res.writeHead(responseCode, {
        'content-type': 'text/html;charset=utf-8',
    });

    res.write(content);
    res.end();

并且,稍后在 fetch() 调用完成后的某个时间,它可能会尝试设置您的 cookie。到那时,已经太晚了,因为已经发送了响应。因此,您的 cookie 永远不会发送。要解决此问题,您必须重组代码,这样如果您要进入调用 fetch() 的分支,那么您根本不会执行上述代码,因此 fetch() 响应处理程序可以发送它想要的响应。


此外,在您尝试设置 cookie 的代码中,您这样做:

res.writeHead(200, { 'Set-Cookie': 'cookie', 'Content-Type': 'text/plain' });
res.writeHead(301, { Location: `http://localhost:53134/?code=${accessCode}` });
res.end();

这完全没有意义。您可以 res.writeHead() 一次且只能一次(您可以在该调用中设置多个 header )。而且,您会得到一个且只有一个请求状态代码,而不是两个。任选其一。