【问题标题】:i want to return a specific response on calling endpoint using express js我想使用 express js 返回调用端点的特定响应
【发布时间】:2023-02-05 07:34:22
【问题描述】:

this is my code that i use to get air quality in the nearest city

this is the response that i get

:i want to return a part of this response and it will be like this

我希望返回一个特殊的响应: 我只想返回这一部分: “污染”: { “ts”:“2023-02-03T06:00:00.000Z”, “aqius”:29, “主要”:“p2”, “aqicn”:10, “maincn”:“p2” }

【问题讨论】:

标签: node.js express axios response


【解决方案1】:

此代码将起作用。

res.send({ result : { pollution : response.data.data.current.pollution } })

这是带有模拟 rest API 调用的演示代码

const express = require("express")
const axios = require('axios')
const cors = require("cors")

const app = express()
app.use(cors())

const API_URL = 'http://localhost:3001/users'

app.get("/whole-data", async (req, res) => {
    const response = await axios.get(`${API_URL}`)
    return res.send(response.data)
});

app.get("/air-quality", async (req, res) => {
    const response = await axios.get(`${API_URL}`)
    return res.send({ result : { pollution : response.data.data.current.pollution } })
});

app.listen(3000, () => { console.log("Listening on :3000") })

仅污染

您需要从浏览器打开

http://localhost:3000/air-quality

得到这个结果

// 20230203112244
// http://localhost:3030/air-quality

{
  "result": {
    "pollution": {
      "ts": "2023-02-03T06:00:00.000Z",
      "aqius": 29,
      "mainus": "p2",
      "aqicn": 10,
      "maincn": "p2"
    }
  }
}

整个数据

您需要从浏览器打开

http://localhost:3000/whole-data

得到这个结果

// 20230203111342
// http://localhost:3000/whole-data

{
  "status": "success",
  "data": {
    "city" : "Inashiki",
    "state" : "Ibaraki",
    "country" : "Japan",
    "location" : {
        "type": "Point",
        "coordinates": [
            140.32356,
            35.95633
        ]
    },
    "current": {
        "pollution": {
            "ts" : "2023-02-03T06:00:00.000Z",
            "aqius" : 29,
            "mainus" : "p2",
            "aqicn" : 10,
            "maincn" : "p2"
        },
        "weather": {
            "ts" : "2023-02-03T07:00:00.000Z",
            "tp" : 6,
            "pr" : 1014,
            "hu" : 70,
            "ws" : 0.89
        }
    }
  }
}

【讨论】:

  • 源代码作为代码上传。在这种情况下,结果作为图像更有效。
  • 我不同意。不确定你的推理,但例如显示 curl 调用和结果作为文本(如有必要,通过管道传输到任何 json 格式化程序)不会排除一些读者知道显示的内容。请阅读链接参考。
  • 好的,我用 JSON 更新了我的答案。没有 curl 调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 2020-07-24
相关资源
最近更新 更多