4

我正在制作一个 angularjs cordova 应用程序。要登录,我们必须向另一个域执行第一个请求,/login并且响应有一个名为的条目cookie,其中包含我们必须设置才能登录的 cookie。

问题是当我开发时ionic serve(所以在我的浏览器中),有一个可怕的东西叫做 CORS。而且由于我要连接的另一个站点不允许 CORS,我被迫使用代理 using node-http-proxy,它代理了请求并添加了 CORS 标头。然后,当我需要连接到另一个网站时,我在我的代理上发出请求。但现在我需要按照前面的说明登录。

所以我把这段代码放到我的代理中,它解析/login路由的响应并简单地提取 cookie:

connect.createServer(
  function(req, res, next) {
    res.oldWrite = res.write;
    var body = ""
    res.write = function(data) {
      body = data.toString('UTF8')
      cookie = (/<cookie><!\[CDATA\[wenvjgol=(.+)\]\]><\/cookie>/g.exec(
        body) || ["", undefined])[1]
      if (cookie) console.log('found cookie: ' + cookie)
      res.oldWrite(data);
    }
    ...
    if (cookie) {
      res.setHeader('Set-Cookie', 'wenvjgol=' + cookie +
        '; Domain=otherwebsite.com; Path=/; Expires=' + new Date(Date.now() +
          1000 * 3600 * 24).toUTCString())
    }
    next();
  },
  function(req, res) {
    if (req.method === "OPTIONS") {
      res.end();
      return;
    }
    proxy.web(req, res);
  }
).listen(8101);

现在,当我到达时,/login我看到
cookie found: 1gmriba47wlc4ow4k88k8o8044gskso8sc4s0c8k40gcs44g8og40c8sks00so8og

由于某些原因,没有在第一个请求上设置 cookie。所以我在另一台服务器的某个地方发出了第一个请求(总是通过代理)。

在响应标头中有

Set-Cookie: wenvjgol=1gmriba47wlc4ow4k88k8o8044gskso8sc4s0c8k40gcs44g8og40c8sks00so8og; Domain=anotherdomain.com; Path=/; Expires=Tue, 21 Oct 2014 11:23:55 GMT

铬检测到它。但是当我想向 url 发出请求并且必须登录时,没有 cookie,不在请求中也不在响应中:(

这就是我在角度上的做法:

$auth.login($event).then (sid) ->
  console.log 'sid is', sid

  $http(
    method: "GET"
    url: "#{config.domain}/forums"
    withCredentials: true
    # headers:
      # "Cookie": "wenvjgol=#{sid}"
  )
.then ->
  $http(
    method: "GET"
    url: "#{config.domain}/forums/5-#{$routeParams.id}-#{$routeParams.topic}-1-0-1-0-0.xml"
    withCredentials: true
    # headers:
      # "Cookie": "wenvjgol=#{sid}"
  )
.then console.log

完整的代理文件在这里:https ://gist.github.com/vinz243/fd01b77ef309101976a5

我希望我很清楚。

4

0 回答 0