如何从Node.js中的HTTP post方法中提取表单数据(form[method="post"])和文件上传?

我看了文件,谷歌了一下,什么都没找到。

function (request, response) {
    //request.post????
}

有图书馆或黑客吗?


当前回答

如果有人试图淹没你的RAM,一定要杀死连接!

var qs = require('querystring');

function (request, response) {
    if (request.method == 'POST') {
        var body = '';
        request.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) { 
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                request.connection.destroy();
            }
        });
        request.on('end', function () {

            var POST = qs.parse(body);
            // use POST

        });
    }
}

其他回答

如果它涉及文件上传,浏览器通常以“multipart/form-data”内容类型发送它。 您可以在这种情况下使用它

var multipart = require('multipart');
multipart.parse(req)

参考1

参考2

要详细说明使用URLSearchParams:

Node.js知识:如何读取POST数据? 类:URLSearchParams .js文档 MDN: URLSearchParams

const http = require('http');

const POST_HTML =
  '<html><head><title>Post Example</title></head>' +
  '<body>' +
  '<form method="post">' +
  'Input 1: <input name="input1"><br>' +
  'Input 2: <input name="input2"><br>' +
  'Input 1: <input name="input1"><br>' +
  '<input type="submit">' +
  '</form>' +
  '</body></html>';

const FORM_DATA = 'application/x-www-form-urlencoded';

function processFormData(body) {
  const params = new URLSearchParams(body);

  for ([name, value] of params.entries()) console.log(`${name}: ${value}`);
}

// req: http.IncomingMessage
// res: http.ServerResponse
//
function requestListener(req, res) {
  const contentType = req.headers['content-type'];
  let body = '';

  const append = (chunk) => {
    body += chunk;
  };
  const complete = () => {
    if (contentType === FORM_DATA) processFormData(body);

    res.writeHead(200);
    res.end(POST_HTML);
  };

  req.on('data', append);
  req.on('end', complete);
}

http.createServer(requestListener).listen(8080);
$ node index.js
input1: one
input2: two
input1: three

如果有人试图淹没你的RAM,一定要杀死连接!

var qs = require('querystring');

function (request, response) {
    if (request.method == 'POST') {
        var body = '';
        request.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) { 
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                request.connection.destroy();
            }
        });
        request.on('end', function () {

            var POST = qs.parse(body);
            // use POST

        });
    }
}

Node.js 18的现代异步方式,零依赖:

server.mjs:

import { createServer } from 'node:http';

const rawReqToString = async (req) => {
    const buffers = [];
    for await(const chunk of req){
        buffers.push(chunk);
    }
    return Buffer.concat(buffers).toString();
};

const server = createServer(async (req, res) => {
    const object = JSON.parse(await rawReqToString(req));
    ...
});

server.listen(3000, 'localhost', () => {
    console.log(`The server is running.`);
})

你可以使用querystring模块:

var qs = require('querystring');

function (request, response) {
    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data;

            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                request.connection.destroy();
        });

        request.on('end', function () {
            var post = qs.parse(body);
            // use post['blah'], etc.
        });
    }
}

现在,例如,如果你有一个名为age的输入字段,你可以使用变量post访问它:

console.log(post.age);