简体   繁体   中英

npm install request has been deprecated

I am new to nodejs and I am trying a simple task or program that builds API to get the current weather of a city from this website: https://openweathermap.org/

i tested the get api in POSTMAN and able to give me the correct result, however when I tried it already in nodejs, the result is "undefined"

this is the code

const request = require("request");

const url = "api.openweathermap.org/data/2.5/weather?q=London,uk&appid=922a0c3b43f4d078f19599ff2fda6";

request(url, (error, response, body) => {
console.log(body)

})

I understand that I should install first the request module using this line

npm install request

But the output says the it is already deprecated. Could it be the reason why is not successful? What should be the workaround?

在此处输入图片说明

Check the status code first before you do the console.log . You can try something like this,

const request = require("request");

const url = "api.openweathermap.org/data/2.5/weather?q=London,uk&appid=922a0c3b43f4d078f19599ff2fda6";

request(url, (error, response, body) => {
   if (!error && response.statusCode == 200) {
        console.log(body) 
   }
})

Thanks to David R suggestion and was able to locate that the problem is my URI is INVALID

should append: http:// in the URI and it worked as expected.

Here is the final code

const request = require("request");

const url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=922a0c3b43f4d078f19599ff2fda6";

request(url, (error, response, body) => {
    if (!error && response.statusCode == 200) {
        console.log(body) 
    }
    else
    {
        console.log(error)
    }
})

Also if you are looking for an alternative package that is not deprecated, the POSTMAN organization has forked the request module and they're continuing to support it, releasing new versions.

www.npmjs.com/package/postman-request

 npm i postman-request

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