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

时间:2018-08-24 05:45:48

标签: node.js api

将值Sydney分配给变量city,现在如何在下面的api端点中发布变量的值并接收适当的json

如果我直接在端点发布值“ Sydney”,那么json返回

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

但是,如果我以$ {city}的身份发布,那么“ Sydney”的值就不会发布,我应该能够发布变量的值

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);
  }
}

2 个答案:

答案 0 :(得分:2)

我认为您正在尝试使用模板文字: 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`

请注意网址字符串附近的引号类型。

答案 1 :(得分:1)

请尝试提到的代码:

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);
    }
  }
});