如何从Node.js中的HTTP post方法中提取表单数据(form[method="post"])和文件上传?
我看了文件,谷歌了一下,什么都没找到。
function (request, response) {
//request.post????
}
有图书馆或黑客吗?
如何从Node.js中的HTTP post方法中提取表单数据(form[method="post"])和文件上传?
我看了文件,谷歌了一下,什么都没找到。
function (request, response) {
//request.post????
}
有图书馆或黑客吗?
当前回答
如果你不想把数据和数据回调放在一起,你可以像这样使用可读回调:
// 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
});
这种方法修改传入的请求,但是一旦您完成响应,请求就会被垃圾收集,因此这应该不是问题。
如果你害怕巨大的身体,一种先进的方法是先检查身体的大小。
其他回答
有很多种方法。然而,我所知道的最快的方法是使用带有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/
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.`);
})
1)从npm安装body-parser。
2)然后在app.ts中
var bodyParser = require('body-parser');
3)然后你需要写
app.use(bodyParser.json())
在app.ts模块中
4)记住你要包括
app.use(bodyParser.json())
在任何模块声明的顶部或之前。
Ex:
app.use(bodyParser.json())
app.use('/user',user);
5)然后使用
var postdata = req.body;
要详细说明使用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
如果你使用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)
});