我正在一個 NodeJS 專案中作業,該專案讀取data.json一個 JSON 檔案,其中包含近百個帶有坐標(緯度和經度)的資料,我想使用這些坐標來顯示天氣和其他東西,使用Open Weather API,之后我需要稍后創建一個包含所有這些物件的陣列,將每個物件添加到資料庫中,我希望從 JSON 中獲取該坐標,然后創建物件,但我收到此訊息錯誤:
file:///X:/X/X/X/X/X/X/node_modules/node-fetch/src/index.js:95
reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error));
^
FetchError: request to https://api.openweathermap.org/data/2.5/weather?lat=undefined&lon=undefined&appid=XX&units=metric&lang=sp failed, reason: read ECONNRESET
at ClientRequest.<anonymous> (file:///X:/X/X/X/X/X/X/node_modules/node-fetch/src/index.js:95:11)
at ClientRequest.emit (node:events:390:28)
at TLSSocket.socketErrorListener (node:_http_client:447:9)
at TLSSocket.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ECONNRESET',
code: 'ECONNRESET',
erroredSysCall: 'read'
}
我帶來了我所有的 JSON,因為當我 console.log 它們時,我把它們拿回來,但我不知道如何使它起作用,這里有一個小例子data.json:
[
[{
"latjson": 1,
"lonjson": 1,
"IdOficina": "1"
}],
[{
"latjson": 2,
"lonjson": 2,
"IdOficina": "2"
}]
]
這是我嘗試將資料從 API 插入到 myObject
async function calcWeather() {
fs.readFile('./json/data.json', 'utf8', function (err, info) {
//console.log(info);
for (var i in info) {
const _idOficina = info[i][0].IdOficina;
const lat = info[i][0].latjson;
const long = info[i][0].lonjson;
const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
fetch(base)
.then((responses) => {
return responses.json();
})
.then((data) => {
var myObject = {
Id_Oficina: _idOficina,
Humedad: data.main.humidity,
Nubes: data.clouds.all,
Sensacion: data.main.feels_like,
Temperatura: data.main.temp,
Descripcion: data.weather[0].description,
};
// validation and saving data to array
if (myObject.Temperatura < 99) {
lstValid.push(myObject);
}
});
}
});
}
當我轉到給我錯誤的 API 鏈接時:
{"cod":"400","message":"wrong latitude"}
EDIT: The issue seems to be that the Latitude isn't being added to the API, because I get all data when I hardcoded the coords
uj5u.com熱心網友回復:
您沒有正確決議陣列。鑒于那里討論的評論和對資料結構的更改,這是要決議的資料:
[
{
"latjson": 1,
"lonjson": 1,
"IdOficina": "1"
},
{
"latjson": 2,
"lonjson": 2,
"IdOficina": "2"
}
]
與其使用for...in你應該真正使用for...of它會讓你變得更容易,并且會讓你在使用其他編碼時不會遇到麻煩。
這就是它的樣子:
const fakeAPIKey = 12342456478;
const data = [{
"latjson": "33.44",
"lonjson": "-94.04",
"IdOficina": "1"
},
{
"latjson": 2,
"lonjson": 2,
"IdOficina": "2"
}
];
for (let item of data) {
let url = `https://api.openweathermap.org/data/2.5/onecall?lat=${item.latjson}&lon=${item.lonjson}&exclude=hourly,daily&appid=${fakeAPIKey}`;
console.log(`Official Id: ${item.IdOficina}`);
console.log(url);
console.log('-----------');
}
uj5u.com熱心網友回復:
{"cod":"400","message":"wrong latitude"} 您從 API 收到錯誤的請求回應。從報錯資訊看緯度不對
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/364491.html
