播放:未设置会话 Cookie。无法使用 Javascript 读取 Cookie

Play: Session Cookie not set. Cannot read Cookie using Javascript

为了将授权令牌(应存储在数据库中)发送到我的服务器,我在我的 .scala.html 文件中进行了 AJAX 调用。

$.ajax({
       url: "http://localhost:9000/storeauthcode",
       type: 'get',
       data: {code: authResult['code']},
       contentType: 'application/json',
       dataType: 'json',
       success: function(result) {
       // Handle or verify the server response.
           console.log("you're fully logged in now.")
           console.log(JSON.stringify(result, null, 2))
           console.log("document.cookie = "+document.cookie)
       },
       error: function (xhr, status, error) {
           console.log("error\n")
           console.log(xhr.responseText)
       }

   });
  }

在服务器端,我存储授权码和return一个json响应

  def storeAuthCode  = Action { request =>
  //store credentials in database
  //...
  //return some data
  Ok(Json.toJson(Map("a"->"b"))).withSession("code"-> "someAuthCode", "id"->"someId")
}

如果我尝试通过

在 AJAX 调用的成功处理程序中打印所有 cookie
console.log("document.cookie = "+document.cookie)

document.cookie 似乎是空的,尽管服务器应该已经创建了一个会话 Cookie(或至少任何东西)。 document.cookie 应该 return 一个“;”我的 Cookie 值的分隔列表。

如何才能成功设置我的 Cookie?

您无法阅读的原因是 HTTPOnly 为 Play 的会话 cookie 设置了标志。

您有几个选项可以改用:

  1. 在JSON对象中发送codeid(如"a"->"b"
  2. 您也可以将它们作为 response headers 发送,这样您就可以在成功回调中获取它们,例如:

    Ok(Json.toJson(Map("a" -> "b")))
      .withHeaders(
        "code" -> "foo",
        "id" -> "bar"
      )
      .withCookies(
        Cookie("code", "foo"),
        Cookie("id", "bar")
      )
    

    jQuery

    success: function(data, textStatus, jqXHR) {
        console.log(jqXHR.getResponseHeader('code'));
        console.log(jqXHR.getResponseHeader('id'));
    },