Express.js提交表单后如何将URL改为localhost:3000/用户输入格式
问题:提交名称后URL格式不符合预期
希望提交名称后,URL更新为localhost:3000/用户输入内容格式,但当前提交后的结果是localhost:3000/?name=用户输入内容,求解决建议。
相关代码
HTML模板文件(name_input.ejs)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function handleSubmit() { let form = document.getElementById("name-form") form.addEventListener("submit", function (event) { event.preventDefault() let name = document.getElementsByName("name")[0].value // 补充http://避免路径解析异常 window.location.href = "http://localhost:3000/" + name }) } // 确保DOM加载完成后绑定提交事件 window.addEventListener('DOMContentLoaded', handleSubmit); </script> </head> <body> <form id="name-form" onsubmit=""> <label for="name">Name:</label> <input type="text" value="Enter your name" id="name" name="name"> <input type="submit" value="Submit" id="name-submit-btn"> </form> </body> </html>
Node.js/Express代码文件
const express = require('express') const app = express() app.set('view engine', 'ejs') app.listen(3000, function () { console.log('Node listening on port 3000') }) app.get('/', (req, res) => { res.render('name_input') }) app.get('/:name', function (req, res) { let name = req.params.name let age = req.query.age if (age === undefined) { res.render('age_input') } else { res.send(`Hello ${name}. You are ${age}`) } }) /*app.get('/age', function (req, res) { res.render('age_input') })*/
解决建议
- 执行表单提交事件绑定函数:原代码中定义的
garbageCollector函数未被调用,导致表单提交时触发默认GET请求,生成带查询参数的URL。需在DOM加载完成后调用该函数,或直接将事件绑定逻辑放在DOMContentLoaded回调中。 - 补充协议前缀:原代码中
window.location.href的目标路径缺少http://前缀,部分浏览器会将其解析为相对路径,添加前缀可确保跳转路径准确。 - 可选优化:若无需额外逻辑处理,也可通过动态修改表单
action属性实现目标路径跳转,但JavaScript拦截提交事件的方式更灵活,适合需要获取用户输入值的场景。
内容的提问来源于stack exchange,提问作者Pham Long
相关产品推荐
相关产品推荐

