我想从这个承诺中获取 json,我该怎么做

发布于 2025-01-16 21:06:56 字数 515 浏览 2 评论 0原文

var url = "https://www.metaweather.com/api/location/2471217/#";
let promise = new Promise((resolve, reject) => {
    fetch(url)
        .then(function (response) {
            return response.json();
        }
        )
        .then(function (json) {
            resolve(JSON.stringify(json))
        })

})

promise.then((message) => {
    console.log(message)
}).catch((message) => {
    console.log(message)
})

我想获取 json 作为字符串。 谢谢你们

p.s 我是 JS 的新手

var url = "https://www.metaweather.com/api/location/2471217/#";
let promise = new Promise((resolve, reject) => {
    fetch(url)
        .then(function (response) {
            return response.json();
        }
        )
        .then(function (json) {
            resolve(JSON.stringify(json))
        })

})

promise.then((message) => {
    console.log(message)
}).catch((message) => {
    console.log(message)
})

I want to get json as string.
thank you guys

p.s I am a newbie for JS

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩心不撩汉 2025-01-23 21:06:56

fetch 已经返回了一个承诺。无需使用 Promise 构造函数。如果您想以文本形式获取响应,则只需调用 response.text(),而不是response.json()

fetch(url)
  .then(response => response.text())
  .then(message => console.log(message))
  .catch(error => console.error(error))

fetch already returns a promise. There is no need to use the Promise constructor. If you want to get the response as text then you can just call response.text(), not response.json():

fetch(url)
  .then(response => response.text())
  .then(message => console.log(message))
  .catch(error => console.error(error))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文