【问题标题】:Set cookie and redirect, without express设置 cookie 和重定向,无需 express
【发布时间】:2015-08-16 18:17:36
【问题描述】:

我希望能够设置一个 cookie,然后使用 node.js 重定向客户端,而不使用 Express 或其他第三方库。网上只能找到使用Express的例子。

当我尝试设置 cookie 并重定向客户端时,cookie 没有设置。但是当我注释掉重定向 res.writeHead(301, {Location: serverAddress}); 时,cookie 被设置,但没有重定向。

那么我该如何设置 cookie,然后直接使用 node.js 重定向客户端?

var fs = require("fs");
var http = require('http');

var home = fs.readFileSync('random.html');

var serverAddress = "http://yourIpAddress";

http.createServer(function(req, res) {
  if(req.url === '/favicon.ico') {
    res.writeHead(200, {'Content-Type': 'image/x-icon'});
    res.end();

  } else if(req.headers.cookie) {

    console.log("Got cookie");

    res.writeHead(200, "OK", {'Content-Type': 'text/html'});
    res.write(home);
    res.end();

  } else {

    console.log('Creating Cookie');

    var cookie = {
      "some": "data"
    };

    res.writeHead(200, {'Set-Cookie': cookie, 'Content-Type': 'text/plain'});

    res.writeHead(301, {Location: serverAddress});

    res.end();

  }
}).listen(80);

【问题讨论】:

  • 快递不能用是什么原因?
  • 我很困惑,难道你不必做"set-Cookie" : "some=data; Expires=Wed, 09 Jun 2021 10:18:14 GMT" 等而不是传入一个对象吗?你确定req.headers.cookie 在没有cookieparser 中间件的情况下被填充。我的观点是你在重新发明轮子,应该使用可用的中间件。
  • @Daemedeor 我看到了那个链接,它只解决了获取和设置 cookie,而不是之后的重定向。
  • @adeno,我不确定"set-Cookie" : "some=data; Expires=Wed, 09 Jun 2021 10:18:14 GMT",但req.headers.cookie 会设置如果您注释掉重定向,并运行服务器两次。

标签: javascript node.js redirect cookies


【解决方案1】:

要在没有Express 的情况下设置cookie 后重定向客户端,只需将要重定向到的URL 传递给res.address

var url = "https://someurl.com";    

res.address(url);

res.end();

【讨论】:

  • res.address 不是节点中的函数,除非我遗漏了什么。
【解决方案2】:

为了避免双重状态设置(200和301,我不确定是否可能)您可以使用META标签HTTP-EQUIV="Refresh"而不是redirectig状态来呈现html页面,例如

var jsrender = require('node-jsrender');

(..)

res.writeHead(200, {'Set-Cookie': cookie, 'Content-Type': 'text/plain'});

// 301 redirection replaced by rendering html template with redirection inside

var tmpl = jsrender.loadFileSync('#redirectTemplate', 'templates/redirect.html')

res.end( tmpl.render() );

redirect.html 看起来像这样

<!DOCTYPE html>
<html>
<head>
<META HTTP-EQUIV="Refresh" CONTENT="1;URL=/redirect-url">
</head>
</html>    

【讨论】:

    猜你喜欢
    • 2016-11-14
    • 2018-08-09
    • 1970-01-01
    • 2012-05-18
    • 2017-07-05
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多