首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从fetch得到字符串吗?

从fetch得到字符串吗?
EN

Stack Overflow用户
提问于 2019-12-21 23:27:45
回答 3查看 91关注 0票数 0

我在想如何从这个抓取中得到一个字符串。到目前为止,我有这样的代码,例如,我希望级别类似于

代码语言:javascript
运行
复制
message.reply(`Your level is ${level}`)

现在我有个代码:

代码语言:javascript
运行
复制
if(args[0]) {
  let krunkerName = args[0]
  const api = `https://apiktracer.herokuapp.com/user/${krunkerName}`;

  fetch(api)
    .then(res => res.text())
    .then(body => console.log(body));

  message.channel.send() //String here

} else {
  message.reply("Please select a user to check stats on")
}

console.log中,当我输入一个名称时(在本例中是mackex5x5 ),就会得到这个结果。

代码语言:javascript
运行
复制
{"stats":{"name":"mackex5x5","id":2858585,"score":2921985,"level":51,"levelProgress":28,"kills":25913,"deaths":5309,"kdr":"4.88","kpg":"19.92","spk":"112.76","totalGamesPlayed":1301,"wins":922,"loses":379,"wl":"0.71","playTime":"3d 26m","funds":22280,"clan":false,"featured":"No","hacker":false,"following":0,"followers":3,"shots":186973,"hits":72936,"nukes":71,"meleeKills":59,"createdDate":"2019-04-13","createdTime":"13:06:00","lastPlayedClass":"Marksman"},"uuid":"3e78ef6b-6121-42db-a112-e6757e5d0bf4","error":"False"}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-12-21 23:35:12

您希望.send.reply在您的.then链中。

代码语言:javascript
运行
复制
if(args[0]) {
  let krunkerName = args[0]
  const api = `https://apiktracer.herokuapp.com/user/${krunkerName}`;

  fetch(api)
  .then(res => res.json())
  .then(body => {
       console.log(body)
       message.reply(`Your level is ${body.stats.level}`) //String here
  });

}else{
  message.reply("Please select a user to check stats on")
}

因为fetch api将来会解析,因为它是异步调用,所以message.channel.sendmessage.reply在解析之前被称为

票数 2
EN

Stack Overflow用户

发布于 2019-12-21 23:35:50

您是在问如何在JavaScript中访问对象中的数据吗?如果是这样的话,您应该是converting the fetch response to a JavaScript object with json() (而不是将其解析为text):

代码语言:javascript
运行
复制
fetch(api)
  .then(res => res.json()) // change text() to json()
  .then(body => message.reply(`Your level is ${body.stats.level}`));
票数 1
EN

Stack Overflow用户

发布于 2019-12-21 23:35:16

使用点语法访问要返回的对象的属性。console.log(body)将成为console.log(body.stats.level)

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59440595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档