如何使用fetch获取Express POST响应并渲染到前端指定HTML元素
问题解决步骤
现有代码问题梳理
- 未阻止表单默认提交行为:点击提交按钮后浏览器会触发原生表单提交,页面刷新导致前端逻辑中断,无法渲染返回结果
- 前端fetch逻辑错误:当前
launchAjax不是可调用的事件处理函数,直接执行了GET请求,没有携带用户输入参数,也没有匹配后端的POST接口 - 响应处理逻辑缺失:后端返回JSON格式的哈希值,前端未做解析直接渲染原始响应对象
修改后的代码
1. app.js 调整
var express = require('express'); var app = express() const path = require('path') const { hashesString, passwordCheck } = require('./bcryptUtil'); // 新增解析JSON请求体的中间件 app.use(express.json()) app.use(express.urlencoded({ extended: true })) app.use(express.static(path.join(__dirname, 'public'))) app.post('/submit-form', (req, res) => { const userInput = req.body.string; hashesString(userInput) .then((output) => { console.log(output); // 直接返回JSON,无需手动序列化 res.json(output) }) .catch(err => { console.log(err) res.status(500).send('哈希生成失败') }) }) app.get('/', function(req, res) { res.sendFile(path.join(__dirname, '/index.html')); }) app.listen(3003);
2. script.js 重写逻辑
const area = document.getElementById("responseArea") const inputEl = document.getElementById("string"); const formEl = document.querySelector('form'); // 绑定表单提交事件,比绑定按钮点击兼容性更好 formEl.addEventListener("submit", launchAjax); function launchAjax(e) { // 阻止表单默认提交刷新页面的行为 e.preventDefault(); const inputValue = inputEl.value.trim(); if (!inputValue) return; // 发起符合要求的POST请求 fetch("/submit-form", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ string: inputValue }) }) .then(response => { if (!response.ok) throw new Error('服务端响应异常') return response.json() }) .then(hashValue => { // 渲染结果到指定区域 area.textContent = `生成的哈希值:${hashValue}`; }) .catch(err => { area.textContent = `错误:${err.message}`; }) }
3. index.html 无需修改,保持原有代码即可
验证方式
重启Node服务后,在页面输入任意字符串点击提交,即可在id为responseArea的区域看到生成的哈希结果。
内容的提问来源于stack exchange,提问作者DeltaFlyer
相关产品推荐
相关产品推荐

