连接天气 api 时出现数据错误

Posted

技术标签:

【中文标题】连接天气 api 时出现数据错误【英文标题】:error in data when i connect a weather api 【发布时间】:2021-07-07 04:30:34 【问题描述】:

这是我第一个使用 node.js 和 express 的应用程序。这是一个基本的应用程序,我连接到外部 API 以显示温度并获取用户输入的“邮政编码和感觉”并将其显示给 UI。我无法获取数据。

我运行应用程序并在邮政编码和感觉文本区域输入数据,我做错了什么?

server.js

// Setup empty JS object to act as endpoint for all routes
projectData = ;
const port = 3000
// Require Express to run server and routes
const express = require("express")
const bodyParser = require("body-parser")
const cors = require("cors")
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded( extended: false ));
app.use(bodyParser.json());

// Cors for cross origin allowance
app.use(cors())
// Initialize the main project folder
app.use(express.static('website'));
app.get('/getWeather',(req,res) => 
    res.send(projectData)
)
app.post('/addWeather',(req,res) => 
    newEntry = 
        data:req.body.data,
        temp: req.body.temp,
        content: req.body.content
    
    projectData = newEntry;
    
)
// Setup Server
app.listen(port, () => 
    console.log(`Your server is running on port $port`);
)

网站/app.js

/* Global Variables */

//const  request  = require("express");

// Create a new date instance dynamically with JS
let d = new Date();
let newDate = (d.getMonth()+1) +'.'+ d.getDate()+'.'+ d.getFullYear();
//let zipcode = document.querySelector("#zip").value;
const APIkey = "2f12ba4132bf221863be475a1a6b34f6";
//let fullURL=`https://api.openweathermap.org/data/2.5/weather?zip=$zipcode&appid=$APIkey$units=metric`


const button1 = document.querySelector("#generate")
button1.addEventListener("click", getDataOfWeather)

function getDataOfWeather()
    const feeling = document.querySelector("#feelings").value;
    const zipcode = document.querySelector("#zip").value;
        getTemp(zipcode)
        .then(function(temp)
             /* console.log(temp);
              addData('/addWeather', data: newDate , temp: temp, content: feeling);*/
             addData(temp,feeling)
        )
        .then(
            updateUI()
        )
     


const getTemp = async(zipcode) => 
    
    try 
        
        if(!zipcode)
            alert("you didnot enter zip code");
        
        const fullURL=`https://api.openweathermap.org/data/2.5/weather?zip=$zipcode&appid=$APIkey&units=metric`
        const res = await fetch(fullURL)
        if(res.status === 200)
            const data = await res.json();
            console.log(data.main.temp);
            return data.main.temp;
            
        else if(res.status === 404)
            alert("error in ZIP code ");
            return false;
       /* const data = await res.json();
        return data;*/
    
    catch (err)
    
        console.log(err);
    

const addData = async(temp,fell) => 
    console.log(fell);
   const response = await fetch("/addWeather",
       method: "POST",
       credentials: "same-origin",
       body:
           data : newDate,
           temp:temp,
           content: fell,
       
   )
   try 
    const nData = await response.json();
    return nData;

catch(err)

          console.log(err);

   

/*const addData = async(url = '', data = )=> 
    const response = await fetch (url , 
        method: 'POST',
        credentials: 'same-origin',
        headers: 
            'content-Type': 'application/json',
        ,
        body: JSON.stringify(data),
    )
    try 
        const nData = await response.json();
        return nData;
    
    catch(err)
    
              console.log(err);
    
*/
const updateUI = async() => 
    const request = await fetch('/getWeather');
    try 
        const allOfData = await request.json();
        console.log(allOfData);
        document.getElementById('data').innerhtml = allOfData.newDate;
        document.getElementById('temp').innerHTML = allOfData.temp;
        document.getElementById('content').innerHTML = allOfData.content;
        

    
    catch (err)
    
        console.log("error",err);
    

网站/index.js

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Journal</title>
<link href="https://fonts.googleapis.com/css?family=Oswald:400,600,700|Ranga:400,700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
 <body>
<div id = "app">
  <div class ="holder headline">
    Weather Journal App
  </div>
  <div class ="holder zip">
    <label for="zip">Enter Zipcode here</label>
    <input type="text" id="zip" placeholder="enter zip code here">
  </div>
  <div class ="holder feel">
    <label for="feelings">How are you feeling today?</label>
    <textarea class= "myInput" id="feelings" placeholder="Enter your feelings here" rows="3" cols="30"></textarea>
    <button id="generate" type = "submit"> Generate </button>
  </div>
  <div class ="holder entry">
    <div class = "title">Most Recent Entry</div>
   <div id = "entryHolder">
    <div id = "date"></div> 
   <div id = "temp"></div>
   <div id = "content"></div>
  </div>
  </div>
  </div>
<script src="app.js" type="text/javascript"></script>

</body>
</html>

【问题讨论】:

所以你有一个错误但决定不实际说出错误信息是什么?为什么,这是秘密?当您将最重要的信息保密时,任何人都可能回答。 @JK 我认为图片说明了一切......控制台中存在错误,并且存在解决该问题所需的所有文件。 【参考方案1】:

您的 ID 是 app.js 中更新 UI 功能中的日期而不是数据

const updateUI = async() => 
    const request = await fetch('/getWeather');
    try 
        const allOfData = await request.json();
        console.log(allOfData);
        document.getElementById('date').innerHTML = allOfData.newDate;  // change data to  date 
        document.getElementById('temp').innerHTML = allOfData.temp;
        document.getElementById('content').innerHTML = allOfData.content;
        

    
    catch (err)
    
        console.log("error",err);
    
 

【讨论】:

当我这样做导致 Ui 未定义

以上是关于连接天气 api 时出现数据错误的主要内容,如果未能解决你的问题,请参考以下文章

运行天气应用程序时出现此错误我正在使用 json 和 http 库来获取数据但我不知道为啥会出现此错误

本地获取 API 时出现自签名证书错误

使用 Pipe (Aerogear) 调用 api 时出现状态码 404 和服务连接错误

Mule Anypoint Studio - 测试连接失败 - 进行连接测试时出现未知错误 - 自定义 API

使用 AWS Amplify 设置 API 连接时出现问题

使用 ESRI arcgis python api 时出现 SSL 错误