【问题标题】:How do I grab the JSON data from a response from a client side GET request?如何从客户端 GET 请求的响应中获取 JSON 数据?
【发布时间】:2021-03-16 02:02:04
【问题描述】:

所以这是我的客户端 GET 请求到服务器以获取一些 JSON 数据。

fetch("/" + "?foo=bar", {
               method: "GET",
               
           }).then(response => {
               console.log("JSON DATA:", response)
           })

这就是我的 GET 请求端点的写法(下半部分是相关部分)

router.get("/", function(req, res) {
        mysql.pool.query("SELECT * FROM workouts", function(err, rows, fields) {
            if (err) {
              console.log(err)
            } else {
                let parsedData = JSON.parse(JSON.stringify(rows))
                for (let entry of parsedData) {
                    // changing 1 and 0 to represent lbs or kg
                    if (entry.lbs == 1) {entry.lbs = "lbs"}
                    else {entry.lbs = "kg"}
                    
                    //formatting the date
                    let formattedDate = new Date(entry.date).toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'});
                    entry.date = formattedDate
                }
              let data = {
                    entry: parsedData
              }
              console.log("REQ.QUERY", req.query)
              if (req.query.foo) {
                  //send JSON data back to client
                  console.log(parsedData)
                  res.json({test:"hello"})
              } else {
                res.render("home", data)
              }
              
            }
          })
})

如您所见,我将 res.json({test:"hello"}) 作为响应。这意味着当我在客户端 console.log(response) 时,它应该提出 {test:"hello"} 对吗?但相反,我得到以下回应。有什么建议?谢谢!!

【问题讨论】:

    标签: javascript node.js json ajax express


    【解决方案1】:

    你得到的是一个Response,它没有直接的响应。你应该打电话给.json

    fetch("/?foo=bar")
        .then(res => res.json())
        .then(res => {
            console.log(res); // already json parsed object
        });
    

    如果您不想解析为 JSON 或有非 json 响应,请改用 .text()

    Read more about fetch here..

    【讨论】:

    • 超级有帮助,谢谢!!另外,据我所知,为什么 res.json() 不需要像下面这样的花括号。 fetch("/?foo=bar") .then(res => {res.json()}) .then(res => { console.log(res); // 已经 json 解析的对象 });
    • 对于箭头函数,当没有大括号时,表示返回表达式。在这种情况下,res.json() 被返回以利用承诺链。
    猜你喜欢
    • 2018-08-28
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多