【问题标题】:Node js(Express framework): not able to print number API from external server to client browserNode js(Express框架):无法将数字API从外部服务器打印到客户端浏览器
【发布时间】:2020-08-28 08:18:07
【问题描述】:

我正在尝试从外部服务器检索天气 API,当我在控制台记录天气 API 的特定数据时,它也会显示在我的命令提示符上。 但是当我使用 get 方法在浏览器上显示该数据时,我只能发送字符串数据,如“描述”:中雨,而不是数字数据,如“温度”:27 它会使应用程序崩溃。

节点js代码:

//jshint esversion:6

const express = require("express");
const app = express();

const https = require("https");


app.get("/", function(req, res) {



  const url = "https://api.openweathermap.org/data/2.5/weather?q=mumbai&appid=d88391210768983e6be06cdd76bdcde3&units=metric";

  https.get(url, function(response) {
    console.log(response.statusCode);

    response.on("data", function(data) {
      const weatherData = JSON.parse(data);
      const temp= weatherData.main.temp;
      const description= weatherData.weather[0].description;
      console.log(temp);
      console.log(description);

      res.send(temp);
    });
  });

});


app.listen(3000, function() {
  console.log("Server is running on port: 3000");
});

【问题讨论】:

    标签: node.js api express


    【解决方案1】:

    理想情况下,您应该返回一个 json。 可以是:

    res.send({temp: temp, description: description});
    

    res.send 必须返回一个字符串/对象/数组/缓冲区。
    你可以这样做:

    res.status(200).send(temp)
    

    但最好发送 json 响应,您也可以对其进行缩放。

    另一种破解方法是:

    res.send("" + temp)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 2020-06-30
      • 2015-10-21
      • 1970-01-01
      • 2012-10-13
      • 2016-05-20
      • 1970-01-01
      相关资源
      最近更新 更多