简体   繁体   中英

i can't figure out why we are using response.on

I've written a code here and I want to know what "response.on" is doing and why we are passing "data", what is this "data". what exactly that ".on" is used for.

const express = require("express");
const https = require("https");
const app = express();
app.get("/",function(req,res){
  const url="https://api.openweathermap.org/data/2.5/weather?q=London&appid=5c8618a9210a11846accc217f3b3084f";
  https.get(url,function(respons){
    response.on("data",function(data){
      const wht = JSON.parse(data)
      temp = wht.main.temp
      res.send("temp   "+ temp)
    })
  })
})
app.listen(3000, function(){
  console.log("running");
});

.on("nameOfEvent", callback) it's a event emitter. So, basically whenever that event is called, that callback will be executed. data is just the name of the event.

  1. In your code there is bug.

You using respons in the argument of function and response inside of function.

  1. Waiting on data of response is documented in https

https://nodejs.org/api/https.html#https_https_get_options_callback

You can read that response is not a classical response from the server but an event listener that listens for stream of data.

It is a low-level interface and in your applications, you should not use them. Lets interest in node-fetch or axios instead if you want only get a response, but not process streams in real-time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM