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

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

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

有图书馆或黑客吗?


当前回答

如果你正在使用Express.js,在你可以访问req. js之前。body,你必须添加中间件bodyParser:

app.use(express.bodyParser());

然后你可以要求

req.body.user

其他回答

如果你更喜欢使用纯Node.js,那么你可以提取POST数据,如下所示:

// Dependencies const StringDecoder = require('string_decoder').StringDecoder; const http = require('http'); // Instantiate the HTTP server. const httpServer = http.createServer((request, response) => { // Get the payload, if any. const decoder = new StringDecoder('utf-8'); let payload = ''; request.on('data', (data) => { payload += decoder.write(data); }); request.on('end', () => { payload += decoder.end(); // Parse payload to object. payload = JSON.parse(payload); // Do smoething with the payload.... }); }; // Start the HTTP server. const port = 3000; httpServer.listen(port, () => { console.log(`The server is listening on port ${port}`); });

如果你使用Express (Node.js的高性能、高级web开发),你可以这样做:

HTML:

<form method="post" action="/">
    <input type="text" name="user[name]">
    <input type="text" name="user[email]">
    <input type="submit" value="Submit">
</form>

API客户端:

fetch('/', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        user: {
            name: "John",
            email: "john@example.com"
        }
    })
});

Node.js:(自Express v4.16.0起)

// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());

// Parse JSON bodies (as sent by API clients)
app.use(express.json());

// Access the parse results as request.body
app.post('/', function(request, response){
    console.log(request.body.user.name);
    console.log(request.body.user.email);
});

Node.js:(对于Express <4.16.0)

const bodyParser = require("body-parser");

/** bodyParser.urlencoded(options)
 * Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
 * and exposes the resulting object (containing the keys and values) on req.body
 */
app.use(bodyParser.urlencoded({
    extended: true
}));

/**bodyParser.json(options)
 * Parses the text as JSON and exposes the resulting object on req.body.
 */
app.use(bodyParser.json());

app.post("/", function (req, res) {
    console.log(req.body.user.name)
});

如果希望表单数据在req.body中可用,则需要使用bodyParser()。 Body-parser解析您的请求并将其转换为可以轻松提取所需相关信息的格式。

例如,假设在前端有一个注册表单。您正在填写它,并请求服务器将详细信息保存在某个地方。

如果使用体解析器,则从请求中提取用户名和密码如下所示。

.............................................................

var loginDetails = {

username : request.body.username,

password : request.body.password

};

对于那些使用原始二进制POST上传没有编码开销,你可以使用:

客户:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/upload", true);
var blob = new Uint8Array([65,72,79,74]); // or e.g. recorder.getBlob()
xhr.send(blob);

服务器:

var express = require('express');
var router = express.Router();
var fs = require('fs');

router.use (function(req, res, next) {
  var data='';
  req.setEncoding('binary');
  req.on('data', function(chunk) {
    data += chunk;
  });

  req.on('end', function() {
    req.body = data;
    next();
  });
});

router.post('/api/upload', function(req, res, next) {
  fs.writeFile("binaryFile.png", req.body, 'binary', function(err) {
    res.send("Binary POST successful!");
  });
});

如果你不想把数据和数据回调放在一起,你可以像这样使用可读回调:

// Read Body when Available
request.on("readable", function(){
  request.body = '';
  while (null !== (request.body += request.read())){}
});

// Do something with it
request.on("end", function(){
  request.body //-> POST Parameters as String
});

这种方法修改传入的请求,但是一旦您完成响应,请求就会被垃圾收集,因此这应该不是问题。

如果你害怕巨大的身体,一种先进的方法是先检查身体的大小。