【问题标题】:Create a cookie in a node.js script在 node.js 脚本中创建一个 cookie
【发布时间】:2021-02-22 13:07:59
【问题描述】:

我正在尝试使用 node.js 脚本。我尝试过使用 express/cookie 解析器 & 没有 ... ATM 我在本地模式下工作,但我将在 webserver 上使用它。

在我所有的尝试中,我得到了任何错误,但 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(200, ...),然后马上做res.writeHead(301, ...)?选择一个或另一个 - 你不能两者都做。一次调用res.writeHead()可以设置多个标头,但只能有一个状态值和一次调用该方法。
  • 另外,您在for 循环中调用res.writeHead(),可能会多次调用它。

标签: javascript node.js express cookies


【解决方案1】:

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

    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() 一次且只能一次(您可以在一次调用中设置多个标头)。而且,您会得到一个请求的状态码,而不是两个。任选其一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多