FormData的使用

jsAPI

#背景

对于这个标签,之前一直没注意它的好处,直到在查阅express如何接受FormData传过来的数据的时候发现了它的方便之处。

#优点

** 能够自动找到form标签下所有带name的表单 **

举例说明

<!-- html 部分 -->
<form>
    <input type="text" name="text" />
    <textarea rows="10" cols="30" name="textarea">
        文本框
    <&#47;textarea>
<&#47;form>
1
2
3
4
5
6
7
// js部分
const form = document.querySelector('form');
const btn = document.querySelector('button');
btn.onclick = function () {
    // 没有写检验
    let data = new FormData(form);
    fetch('./supply', {
            body: data,
            cache: 'no-cache',
            credentials: 'same-origin',
            method: 'POST'
        })
        .then(function (response) {
            return response.json();
        })
        .then(function (myJson) {
            console.log(myJson);
        });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

{% note info %}
只需要获取form的节点,它就能自动获取含有name的表单
{% endnote %}

{% note warning %}
值得注意的是——在表单禁用的时候是不能获取到里面的值
例如
&lt;input type="text" name="text" disabled &#47;&gt;
{% endnote %}

#express获取FormData传过来的值

其实下载一个模块就可以了,connect-multiparty

// 使用方法
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();
router.post('/', multipartMiddleware, (req, res, next) => {
    console.log(req.body); // 查看req.body就可以看传过来的值了
    res.send(req.body);
});
1
2
3
4
5
6
7
Last Updated:5/25/2024, 2:23:06 AM