如何获取Node.JS字段值(提交的表单数据)

How get Node.JS fields value (submitted form data)

我使用 Node.js 没有框架(without-express)。

我当前的代码。

const { headers, method, url } = req;
  let body = [];
  req.on('error', (err) => {
    console.error(err);
  }).on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
     console.log(body)
    body = Buffer.concat(body).toString();

    console.log(body)
    res.writeHead(200, {'Content-Type': 'text/html\; charset=utf-8'});
    res.write(body)
    res.end()
  });

回应

------WebKitFormBoundaryAExpj6oapW6tzLe8
Content-Disposition: form-data; name="field-one"

Test value of field one
------WebKitFormBoundaryAExpj6oapW6tzLe8
Content-Disposition: form-data; name="field-two"

Test value of field-two
------WebKitFormBoundaryAExpj6oapW6tzLe8--

在这个测试例子中,字段一的值为Test value of field one,字段二的值为Test value of field two如何通过字段名获取该字段的值?

NPM 模块是可以接受的。

NPM module are acceptable

您可以使用 parse-formdata 包。

const parseFormdata = require('parse-formdata')
const http = require('http')

http.createServer((req, res) => {
    parseFormdata(req, (err, data) => {
        if (err) {
            // Set whatever status code you want
            return res.end('Error...');
        }
        console.log('fields:', data.fields)
        data.parts.forEach(function(part) {
            console.log('part:', part.fieldname)
        });

        res.writeHead(200, {
            'Content-Type': 'text/html\; charset=utf-8'
        });

        res.end();
    });

}).listen(8080)

如果你想自己学习解析表单数据,你可以阅读那个包的代码。