玩:会话Cookie未设置。使用JavaScript的Cookie无法读取 [英] Play: Session Cookie not set. Cannot read Cookie using Javascript
问题描述
为了给授权令牌(应当被存储在数据库中)发送到我的服务器,我在我的.scala.html文件AJAX调用。
In order to send an authorization token (that should be stored in a database) to my server, I do an AJAX call in my .scala.html file.
$.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)
}
});
}
在服务器端,我存储在auth code,并返回一个JSON响应
On the server side, I store the auth code and return a json response
def storeAuthCode = Action { request =>
//store credentials in database
//...
//return some data
Ok(Json.toJson(Map("a"->"b"))).withSession("code"-> "someAuthCode", "id"->"someId")
}
如果我尝试通过
console.log("document.cookie = "+document.cookie)
的document.cookie看来虽然服务器应该创建一个会话cookie(或至少是任何东西)是空的。的document.cookie应该返回一个;我的Cookie的值分隔的列表。
document.cookie seems to be empty although the server should have created a session Cookie (or at least anything). document.cookie should return a ";" separated list of my Cookie values.
我怎样才能成功地把我的饼干?
How can I set my Cookies successfully?
推荐答案
为什么你不能看,这是的 仅Http
标志设置播放的会话cookie。
The reason why you can't read this is HTTPOnly
flag set for Play's session cookie.
您有几种选择,你可以改用:
You have several options which you can use instead:
- 发送
code
和ID
中的JSON对象(如一 - >B
) -
您也可以送他们作为
响应头
,所以你可以在你的成功回调中得到他们这样的:
- Send
code
andid
in the JSON object (like"a"->"b"
) You can also send them as
response headers
so you can get them within your success callback like:
Ok(Json.toJson(Map("a" -> "b")))
.withHeaders(
"code" -> "foo",
"id" -> "bar"
)
.withCookies(
Cookie("code", "foo"),
Cookie("id", "bar")
)
jQuery的
jQuery
success: function(data, textStatus, jqXHR) {
console.log(jqXHR.getResponseHeader('code'));
console.log(jqXHR.getResponseHeader('id'));
},
这篇关于玩:会话Cookie未设置。使用JavaScript的Cookie无法读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!