如何使用Axios发送表单POST请求?前端新手入门问题求解
实现方案
现有代码问题梳理
- HTML元素id不匹配:输入框id为
setPrize,但JS中用getElementById("myInput")找不到对应元素 - 事件绑定逻辑错误:直接将axios请求的执行结果赋值给
onchange,会导致页面加载时就自动发请求,不是输入内容触发时才发送 - HTML语法错误:第二个输入框错用了
</button>作为结束标签,空的form标签没有实际作用可移除 - 后端大概率缺少解析JSON请求的中间件,导致拿不到
req.body的值
修正后的代码
1. HTML代码
<!-- 输入stanza的文本框 --> <input class="btn btn-primary mx-auto h-8 app-title mt-2 bg-purple-600 rounded-lg p-4 text-center overflow-hidden xl:my-4 xl:px-4 w-1/6 placeholder-white" id="setPrize" type="text" placeholder="Enter a stanza" /> <!-- 触发请求的按钮 --> <button class="btn btn-primary mx-auto h-8 app-title mt-2 bg-purple-600 rounded-lg p-4 text-center overflow-hidden xl:my-4 xl:px-4 w-1/6 placeholder-white" onclick="sendStanza()" >Victim</button> <input class="btn btn-warning mx-auto h-8 app-title mt-2 bg-purple-600 rounded-lg p-4 text-center overflow-hidden xl:my-4 xl:px-4 w-1/6" id="prize" type="text" onclick="clearOutput()" /> <div class="panel-body" id="getResult1"></div>
2. 前端JS代码(包含Axios逻辑)
// 发送请求的函数,点击按钮时触发 function sendStanza() { // 实时获取输入框里的内容 const inputContent = document.getElementById('setPrize').value; // 发POST请求,把输入框内容放到请求体里 axios.post('/Stanza', { stanza: inputContent }) .then(function (response) { // 后端返回的内容打印到控制台,也可直接显示在页面上 console.log('请求成功,返回内容:', response.data); document.getElementById('getResult1').innerText = '提交成功:' + response.data.stanza; }) .catch(function (error) { console.log('请求出错:', error); }) } // 清空功能实现 function clearOutput() { document.getElementById('prize').value = ''; document.getElementById('getResult1').innerText = ''; }
3. Express后端代码补充
必须在app.post之前加JSON解析中间件,否则req.body会是undefined
// 加在所有路由定义之前,用于解析JSON格式的请求体 app.use(express.json()); // 原有POST接口无需修改 app.post('/Stanza', function(req, res) { console.log('receiving data ...'); console.log('body is ',req.body); res.send(req.body); });
效果说明
现在你在第一个输入框输入任意内容,点击Victim按钮就会把输入的内容通过POST请求发送给后端,后端可以直接从req.body.stanza拿到你输入的内容,返回结果也会显示在页面的getResult1区域。
内容的提问来源于stack exchange,提问作者Bacon Bacon
相关产品推荐
相关产品推荐

