客户端:
<body>
<form id="form">
<input type="text" class="uname">
<input type="password" class="password">
<input type="button" value="提交" id="btn">
</form>
<script>
var form = document.querySelector('#form');
var btn = document.querySelector('#btn');
btn.addEventListener('click', function () {
//将普通的HTML表单转化为表单对象
var formData = new FormData('form')
console.log(formData.get('uname'));
//创建ajax对象
var xhr = new XMLHttpRequest();
xhr.open('post', 'http://localhost:3000/formData');
xhr.send(formData);
xhr.onload = function () {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
})
</script>
</body>
服务器端:
const formidable = require('formidable');
app.post('/formData', (req, res) => {
// 创建formidable表单解析对象
const form = new formidable.IncomingForm();
// 解析客户端传递过来的FormData对象
form.parse(req, (err, fields, files) => {
res.send(fields);
});
});
问题反馈: