我正在尝试制作一个天气应用程序,并且我正在使用一个天气API来获取信息,但是当我试图解析JSON数据时出现了这个错误: https edit:我需要从SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at IncomingMessage.<anonymous>请求中获取经度值和经度值。我试着返回它,但它仍然显示lon和lat is undefined。
第二次编辑:如果我输入lon和LAT值,它将解析数据并发送回JSON,但我需要https请求时locaionIQ API中的lon和LAT值。如何获取这些值?代码如下:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const https = require('https');
const { static, response } = require('express');
require('dotenv').config();
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static('public'))
app.listen(3000, ()=>{
console.log("server is running on port 3000")
})
app.get('/', (req,res)=>{
res.sendFile(__dirname+'/index.html')
})
app.post('/', (req,res)=>{
let apiKeyLocationIQ = process.env.API_KEY_LOCATIONIQ;
let apiKeyWeather = process.env.API_KEY_WEATHER;
let cityLocationIQ = req.body.citySearch;
let urlLocationIQ = "https://api.locationiq.com/v1/search.php?format=JSON&key="+apiKeyLocationIQ+"&q="+cityLocationIQ+"&limit=1";
https.get(urlLocationIQ, function(response){
response.on("data",function(data){
let locationIQ = JSON.parse(data);
const lat= locationIQ[0].lat;
const lon= locationIQ[0].lon;
const cityName = locationIQ[0].display_name;
})
})
let urlWeather = 'https://api.openweathermap.org/data/2.5/onecall?&lat='+lat+'&lon='+lon+'&exclude=alerts,minutely&units=metric&appid='+apiKeyWeather+'&lang=en&cnt=7';
https.get(urlWeather, function(response){
response.on("data",function(data){
let weatherData = JSON.parse(data);
console.log(weatherData);
})
})
})发布于 2021-01-07 10:24:38
在Node下,HTTP/HTTPS请求数据可以以多个块的形式到达,在解析得到的JSON字符串之前需要合并这些块。
本质上,JSON解析需要在on("end", callback)中执行,而不是在on("data", callback)中执行,否则可能会有不完整的JSON文本的风险。
Node文档提供了一个在http.get(options[, callback])下获取JSON数据的极好的工作示例。由于HTTP和HTTPS API的相似之处,在文档的HTTPS部分中似乎没有重复。
发布于 2021-11-08 19:39:11
Https响应数据是分块收集的,所以当它收集数据时("on"),我们应该将数据(字符串)附加到变量中(这里以空字符串开头,让chunks="";)
当收集完所有数据块("end")时,我们最终应该将字符串(API数据)解析为JSON格式。
https.get(apiLink, function (response) {
let chunks="";
response.on("data", function (chunk) {
chunks+=chunk;
});
response.on("end", function(){
// console.log("API Data recieved");
let defaultCovidData = JSON.parse(chunks);
// code after parse string into JSON format
});
});https://stackoverflow.com/questions/65605567
复制相似问题