首页 > 解决方案 > 使用开放天气图 api/ 时出现 401 错误

问题描述

我正在尝试制作天气应用程序,但出现此错误。 错误

enter code here
const express =require("express");
const https=require("https");
const bodyParser=require("body-parser");
const app=express();
app.use(bodyParser.urlencoded({extended: true}));

app.get("/",function(req,res){
res.sendFile(__dirname+"/index.html");
});
app.post("/",function(req,res)
{
  const query=req.body.CityName;
  const api_key="658767b0ae936b022f59a69f44868419"
  const unit="metric";
const url="https://api.openweathermap.org/data/2.5/weather?q="+query+"&appid="+"&units="+unit;
https.get(url,function(response){
  console.log(response.statusCode);
  response.on("data",function(data)
{
const weather_data=  JSON.parse(data);
console.log(weather_data);
const temp=weather_data.main.temp
const icon=weather_data.weather[0].icon
const icon_id=" http://openweathermap.org/img/wn/"+icon+"@2x.png"
res.write("Temp="+temp);
res.write("<img src="+icon_id+">");
res.send();
})
});
})

API 密钥有效,因为我尝试使用它(https://api.openweathermap.org/data/2.5/weather?q=Trivandrum&appid=658767b0ae936b022f59a69f44868419&units=metric

标签: javascripthtmlcssapi

解决方案


欢迎来到stackoverflow。

您已经定义了一个名为 api_key 的常量:

const api_key="658767b0ae936b022f59a69f44868419"

但你从不使用它。

您需要更改您的查询以包含您的 api_key 作为 appid:

const url="https://api.openweathermap.org/data/2.5/weather?q="+query+"&appid="+api_key+"&units="+unit;

推荐阅读