![](/img/trans.png)
[英]SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)
[英]SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at IncomingMessage.<anonymous>
Im trying to make a weather app and I'm using a weather API to get the information but this error shows up when I'm trying to parse the JSON data: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at IncomingMessage.<anonymous>
编辑:我需要从 https 请求中获取 lat 和 lon 值。 我尝试返回它,但它仍然会说 lon 和 lat 未定义。
第二次编辑:如果我输入 lon 和 lat 的值,它将解析数据并发回 JSON 但我需要 Z5E056C500A501C4B6BADE57180 请求中来自 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);
})
})
})
在 Node 下, HTTP/HTTPS
请求数据可以以多个块的形式到达,这些块需要在解析生成的 JSON 字符串之前进行合并。
本质上 JSON 解析需要在on("end", callback)
中执行,而不是在on("data", callback)
中执行,否则有不完整的 JSON 文本的风险。
节点文档有一个很好的工作示例,用于在http.get(options[, callback])下获取 JSON 数据。 由于HTTP
和HTTPS
API 的相似性,这在文档的 HTTPS 部分中似乎没有重复。
Https 响应数据是按小块收集的,所以当它收集数据时(“on”),我们应该 append 变量中的数据(字符串)(以空字符串开头 [here let chunks="";])
当所有数据块都收集完毕(“结束”)后,我们应该最终将字符串(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
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.