如何在 API 端点链接中发布变量的值?



将值悉尼分配给变量城市,现在我如何在下面的 api 端点中发布变量的值并接收适当的 json

如果我直接在端点发布值"悉尼",则 json 返回

http://api.openweathermap.org/data/2.5/weather?q=madurai&units=metric&appid={API_KEY}

但是如果我发布为 ${city},那么值"悉尼"不会被发布,我应该能够发布变量的值

http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid={API_KEY}

let city = "Sydney" ;  //here this value must be posted in the below link
http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid={API_KEY}
request(url, function (err, response, body) {
if(err)
{
console.log(err);
} 
else 
{
let weather = JSON.parse(body)
if(weather.main == undefined)
{
console.log("undefined");
} 
else 
{
console.log(weather);
}
}

我认为您正在尝试使用模板文字: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

你不只需要做:

const city = "Sydney"
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=9ae40b8fdec0b4d7bc95aa14b4393ce3`

请注意 url 字符串周围的引号类型。

请尝试提到的代码:

var request   = require("request");
let city = "Sydney" ;  //here this value must be posted in the below link
let url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=9ae40b8fdec0b4d7bc95aa14b4393ce3"
console.log(url);
request(url, function (err, response, body) {
if(err) {
console.log(err);
} else  {
let weather = JSON.parse(body)
if(weather.main == "undefined") {
console.log("undefined");
} else {
console.log(weather);
}
}
});

最新更新