我正在尝试从REST API访问JSON数据(在[[R中)。
为了验证自己的身份,我需要在https://dashboard.server.eu/login中使用POST方法。需要发送的数据是电子邮件和密码:library(httr)
login <- list(
email = "[email protected]",
password = "mypass"
)
res <- POST("https://dashboard.server.eu/login", body = login, encode = "form", verbose())
执行上述操作时,得到以下输出:
-> POST /login HTTP/1.1 -> Host: dashboard.server.eu -> User-Agent: libcurl/7.59.0 r-curl/3.3 httr/1.4.1 -> Accept-Encoding: gzip, deflate -> Cookie: session=10kq9qv1udf0107F4C70RY14fsum41sq50 -> Accept: application/json, text/xml, application/xml, */* -> Content-Type: application/x-www-form-urlencoded -> Content-Length: 53 -> >> email=my%40email.com&password=mypass <- HTTP/1.1 200 OK <- access-control-allow-headers: Accept, Authorization, Content-Type, If-None-Match <- access-control-allow-methods: HEAD, GET, POST, PUT, DELETE <- cache-control: no-cache <- content-encoding: gzip <- content-type: application/json; charset=utf-8 <- date: Mon, 09 Mar 2020 14:58:31 GMT <- set-cookie: session=10kq9qv1udf0107F4C70RY14fsum41sq50; HttpOnly; SameSite=Strict; Path=/ <- vary: origin,accept-encoding <- x-microserv: NS4yNi4xODQuMjE3 <- x-poweredby: Poetry <- Content-Length: 2346 <- Connection: keep-alive
该站点的文档说,如果成功,将返回JSON中的示例,然后我应该这样做:res
,并在res.data._id
中包含一个字符串标记。我找不到它,即使查看
res
的每个列表(和子列表)。我应该如何找到令牌?
下面是文档,以及
AngularJS
// Create JSON Object with your token
let authorizeObject = {
'Authorization': 'Session ' + token,
'content-type': 'application/json;charset=UTF-8',
'accept': 'application/json,text/plain',
};
// Create header from the previous JSON Object
let header = {'headers':authorizeObject};
// Use the header in your http request...
$http.get('https://dashboard.server.eu/', header)
是否有实现这个梦想的暗示?使用cURL,我可以检查是否返回了UPDATE-
_id
键/值…使用命令:curl -k -X POST "https://dashboard.server.eu/login" \
-d '{ "email" : "[email protected]", "password" : "mypass" }' \
-H "Content-Type: application/json"
我得到输出:
{ "_id": "697v2on4ll0107F4C70RYhosfgtmhfug", "isAuthenticated": true, "user": { "_id": "5dd57868d83cfc000ebbb273", "firstName": "me", "lastName": "Me", ...
因此,会话令牌确实在某处...这对我有帮助吗?
res
的图像,在content
下显示消息是-只是内容存储为原始字节的向量,这就是为什么您无法识别的原因它作为json。
由于http可以发送任何文件类型,出于各种原因,httr
响应对象中的内容将以原始格式而不是字符串存储-也许最重要的是因为许多二进制文件将包含0x00
字节,在R中的字符串中是不允许的。在您的情况下,我们不仅可以说出res$content
是
文本,而且还可以说是您的“缺失” json。res$content
的前六个字节显示在图像中,即7b, 22, 5f, 69, 64, 22
。通过执行以下操作,我们可以将它们转换为R中的字符串:rawToChar(as.raw(c(0x7b, 0x22, 0x5f, 0x69, 0x64, 0x22)))
[1] "{\"_id\""
这与您期望的json字符串的前六个字符匹配。
因此,如果您这样做:
httr::content(res, "text")
或
rawToChar(res$content)
您将以字符串形式获取json。