You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js Web应用调试求助:表单提交无渲染仅返回304状态码

问题排查与修复方案

你的Web应用功能失效主要由几个关键错误导致,304状态码是浏览器静态资源缓存的正常响应,并非功能失效的直接原因,以下是具体问题和修复步骤:


1. 脚本类型错误导致JS完全未执行

HTML中引入index.js的script标签类型设置错误,浏览器会将其识别为JSON数据而非可执行脚本,直接跳过了JS代码的运行:

<!-- 错误写法 -->
<script src="../index.js" type="application/json" defer></script>

<!-- 修正后 -->
<script src="../index.js" type="text/javascript" defer></script>

2. DOM元素选择器不匹配,无法渲染内容

receiveData函数中使用getElementById获取元素,但HTML中对应的展示元素仅设置了class,未添加id属性,导致无法找到目标DOM节点:

<!-- 错误写法 -->
<div class="data">
    <div class="lat"></div>
    <div class="lng"></div>
    <div class="country"></div>
</div>

<!-- 修正后 -->
<div class="data">
    <div id="lat" class="lat"></div>
    <div id="lng" class="lng"></div>
    <div id="country" class="country"></div>
</div>

3. Promise链断裂,数据未同步完成就执行渲染

调用postData时未返回Promise,导致后续的receiveData会在POST请求还未完成、后端数据未更新时就执行,此时获取到的是空数据:

// 错误写法
getCountryInfo(URL, city, username)
    .then(function (info) {
        postData("/add", { lat: info.lat, lng: info.lng, country: info.country })
    }).then(function () {
        receiveData()
    })

// 修正后(添加return,让Promise链等待POST请求完成)
getCountryInfo(URL, city, username)
    .then(function (info) {
        return postData("/add", { lat: info.lat, lng: info.lng, country: info.country })
    }).then(function () {
        receiveData()
    })

4. 额外优化:API返回空数据时的错误处理

getCountryInfo中未判断API返回的geonames数组是否为空,若输入无效城市会直接报错,建议添加前置判断:

const getCountryInfo = async (URL, city, username) => {
    const res = await fetch(`${URL}q=${city}&username=${username}`);
    try {
        const info = await res.json();
        // 新增判断,避免数组为空时读取[0]报错
        if (!info.geonames || info.geonames.length === 0) {
            throw new Error('未找到对应城市');
        }
        return info['geonames'][0];
    }
    catch (error) {
        console.log("error", error);
        throw error; // 抛出错误让外层catch捕获并提示用户
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:11:07