You need to enable JavaScript to run this app. Async JavaScript气象服务端应用出现unexpected end of input错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Async JavaScript气象服务端应用出现unexpected end of input错误如何解决

错误原因说明

uncaught syntax error: unexpected end of input 是JavaScript语法错误,指JS引擎解析代码到文件末尾时,还没找到预期的闭合符号(花括号、括号、引号等),说明代码存在未闭合的语法结构。

首先修复直接触发报错的问题

你当前app文件末尾的UpdateSite函数只有声明头部,没有函数体和闭合花括号,是直接触发报错的原因,补全即可:

// 原代码只有声明行,补充函数体和闭合符号
function UpdateSite (data) {
  // 补全你的页面更新逻辑,示例如下,选择器可替换为你实际的HTML元素ID
  document.querySelector('#date').innerHTML = data.date
  document.querySelector('#temp').innerHTML = data.temp
  document.querySelector('#content').innerHTML = data.feel
}

其他需要修复的语法/逻辑错误

前端app.js部分

  • 变量名错误:点击事件里拿到的邮编变量是Zcode,但getTemp函数的fetch链接里写的是zipCode,会报变量未定义
  • 方法调用错误:getTemp里调用res.json是方法,缺少括号,正确写法为await res.json()
  • 接口地址错误:openweathermap的接口地址问号位置错误,应为weather?zip=而非weather=?zip=
  • 拼写错误:DealingWithServer函数里的JSON.stringfy拼写错误,正确写法为JSON.stringify
  • 作用域错误:DealingWithServer里直接调用的temp和feel属于其他函数作用域,未传递的情况下无法读取
  • 异常捕获无效:你用try/catch包裹的是同步代码,内部的.then异步链抛出的错误无法被捕获,建议统一用async/await写法简化逻辑

后端server.js部分

  • /recievePOST接口处理完逻辑后没有返回响应,会导致前端请求超时,需要补充res.send()
  • 已定义port变量为3000,但listen时硬编码了端口号,建议统一变量引用

修复后参考代码

前端app.js

/* Global Variables */
const apiKey = "726f360f99f8ed5ce834f19b2f632fd3"
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = (d.getMonth()+1)+'.'+ d.getDate()+'.'+ d.getFullYear();
const gen = document.querySelector("#generate");
gen.addEventListener("click", async() =>{
    const Zcode = document.querySelector("#zip").value;
    const feel = document.querySelector("#feelings").value;
    // 非空校验避免无效请求
    if(!Zcode) return alert('请输入邮编')
    try {
        // 统一用async/await写法,逻辑更清晰
        const temp = await getTemp(Zcode)
        const serverData = await DealingWithServer(newDate, temp, feel)
        UpdateSite(serverData)
    }catch(error){
        console.log('请求出错:', error);
    }
});
async function getTemp (zipCode){
    const res = await fetch (`https://api.openweathermap.org/data/2.5/weather?zip=${zipCode}&appid=${apiKey}&units=metric`);
    if(!res.ok) throw new Error('获取天气信息失败')
    const data= await res.json();
    return data.main.temp
}
async function DealingWithServer (date, temp, feel){
    await fetch('/recieve', {
        method: "POST",
        credentials: "same-origin",
        headers: {"Content-Type": "application/json"},
        body:JSON.stringify({
            date: date,
            temp: temp,
            feel: feel
        })
    });
    const Sres = await fetch('/get', {credentials: "same-origin"});
    if(!Sres.ok) throw new Error('获取服务端数据失败')
    const Sdata = await Sres.json()
    return Sdata;
}
function UpdateSite (data) {
    document.querySelector('#date').textContent = `日期:${data.date}`
    document.querySelector('#temp').textContent = `温度:${data.temp}℃`
    document.querySelector('#content').textContent = `感受:${data.feel}`
}

后端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("/get",(req, res) => {
    res.send(projectData)
})
app.post("/recieve", (req, res) => {
    projectData = req.body
    res.status(200).send({code:0, msg:'保存成功'})
})
// Setup Server
app.listen(port,() =>{
    console.log(`Server running on port ${port}`);
})

内容的提问来源于stack exchange,提问作者AutisitcWebDeveloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 21:54:06