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

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

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

有图书馆或黑客吗?


当前回答

您可以使用express中间件,该中间件现在内置了体解析器。这意味着你所需要做的就是:

import express from 'express'

const app = express()

app.use(express.json())

app.post('/thing', (req, res) => {
  console.log(req.body) // <-- this will access the body of the post
  res.sendStatus(200)
})

该代码示例是带有Express 4.16.x的ES6

其他回答

有很多种方法。然而,我所知道的最快的方法是使用带有body-parser的Express.js库。

var express = require("express");
var bodyParser = require("body-parser");
var app = express();

app.use(bodyParser.urlencoded({extended : true}));

app.post("/pathpostdataissentto", function(request, response) {
  console.log(request.body);
  //Or
  console.log(request.body.fieldName);
});

app.listen(8080);

这可以用于字符串,但我要更改bodyParser。urlencoded to bodyParser。如果POST数据包含json数组,则改为json。

更多信息:http://www.kompulsa.com/how-to-accept-and-parse-post-requests-in-node-js/

限制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

        });
    }
}

如果你不想使用整个框架,如Express,但你也需要不同种类的表单,包括上传,那么formaline可能是一个不错的选择。

它列在Node.js模块中

你可以使用body-parser, Node.js的body解析中间件。

第一个负载体解析器

$ npm install body-parser --save

一些示例代码

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


app.use(function (req, res) {
  var post_data = req.body;
  console.log(post_data);
})

更多文档可以在这里找到