5. FormData
作用:
1.模拟HTML表单,相当于将HTML表单映射成表单对象,自动将表单对象中的数据拼接成请求参数格式
2.异步上传二进制文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 创建html表单 -->
<!-- 必须要有name属性 -->
<form action="" id="form">
<input type="text" name="username" autocomplete='username'>
<input type="password" name="password" autocomplete='password'>
<input type="button" id="btn" value="提交">
</form>
<script type="text/javascript">
//获取按钮
var btn = document.getElementById('btn');
//获取表单
var form = document.getElementById('form');
//为按钮添加点击事件
btn.onclick = function(){
//将html表单转换为表单对象
var formData = new FormData(form);
// 创建ajax对象
var xhr = new XMLHttpRequest();
//对ajax对象进行配置
xhr.open('post','http://localhost:5001/formData');
//发送ajax请求
xhr.send(formData);
xhr.onload = function(){
//对象http状态码进行判断
if (xhr.status == 200){
console.log(xhr.responseText);
}
}
}
//12FormData表单.html
</script>
</body>
</html>
app.js文件
需要安装formidable 命令:npm install --save formidable
//引入express框架
const express = require('express');
//路径处理模块
const path = require('path');
const formidable = require('formidable');
// const bodyParser = require('body-parser'); //接受post请求的第三方模块
//创建web服务器
const app = express();
//静态资源访问服务功能
app.use(express.static(path.join(__dirname , 'public')));
//创建路由
app.post('/formData',(req,res) =>{
//创建formidable表单解析对象
const form = new formidable.IncomingForm();
//解析客户端传递过来的FormData对象
form.parse(req,(err,fields,files) => {
res.send(fields);
})
});
//监听端口
app.listen(5001);
//控制台提示
console.log('服务器启动成功');