如何从Node.js中的HTTP post方法中提取表单数据(form[method="post"])和文件上传?
我看了文件,谷歌了一下,什么都没找到。
function (request, response) {
//request.post????
}
有图书馆或黑客吗?
如何从Node.js中的HTTP post方法中提取表单数据(form[method="post"])和文件上传?
我看了文件,谷歌了一下,什么都没找到。
function (request, response) {
//request.post????
}
有图书馆或黑客吗?
当前回答
要详细说明使用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
其他回答
在像这样的表单字段上
<input type="text" name="user[name]" value="MyName">
<input type="text" name="user[email]" value="myemail@somewherefarfar.com">
上面的一些答案会失败,因为它们只支持平面数据。
现在我正在使用Casey Chu的答案,但使用“qs”而不是“querystring”模块。这也是“体解析器”使用的模块。所以如果你想要嵌套数据,你必须安装qs。
npm install qs --save
然后像这样替换第一行:
//var qs = require('querystring');
var qs = require('qs');
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);
console.log(post.user.name); // should work
// use post['blah'], etc.
});
}
}
我找到了一个视频,它解释了如何实现这一点: https://www.youtube.com/watch?v=nuw48-u3Yrg
它使用默认的“http”模块以及“querystring”和“stringbuilder”模块。应用程序从网页中获取两个数字(使用两个文本框),并在提交时返回这两个数字的和(以及在文本框中持久化的值)。这是我能在其他地方找到的最好的例子。
相关源代码:
var http = require("http");
var qs = require("querystring");
var StringBuilder = require("stringbuilder");
var port = 9000;
function getCalcHtml(req, resp, data) {
var sb = new StringBuilder({ newline: "\r\n" });
sb.appendLine("<html>");
sb.appendLine(" <body>");
sb.appendLine(" <form method='post'>");
sb.appendLine(" <table>");
sb.appendLine(" <tr>");
sb.appendLine(" <td>Enter First No: </td>");
if (data && data.txtFirstNo) {
sb.appendLine(" <td><input type='text' id='txtFirstNo' name='txtFirstNo' value='{0}'/></td>", data.txtFirstNo);
}
else {
sb.appendLine(" <td><input type='text' id='txtFirstNo' name='txtFirstNo' /></td>");
}
sb.appendLine(" </tr>");
sb.appendLine(" <tr>");
sb.appendLine(" <td>Enter Second No: </td>");
if (data && data.txtSecondNo) {
sb.appendLine(" <td><input type='text' id='txtSecondNo' name='txtSecondNo' value='{0}'/></td>", data.txtSecondNo);
}
else {
sb.appendLine(" <td><input type='text' id='txtSecondNo' name='txtSecondNo' /></td>");
}
sb.appendLine(" </tr>");
sb.appendLine(" <tr>");
sb.appendLine(" <td><input type='submit' value='Calculate' /></td>");
sb.appendLine(" </tr>");
if (data && data.txtFirstNo && data.txtSecondNo) {
var sum = parseInt(data.txtFirstNo) + parseInt(data.txtSecondNo);
sb.appendLine(" <tr>");
sb.appendLine(" <td>Sum: {0}</td>", sum);
sb.appendLine(" </tr>");
}
sb.appendLine(" </table>");
sb.appendLine(" </form>")
sb.appendLine(" </body>");
sb.appendLine("</html>");
sb.build(function (err, result) {
resp.write(result);
resp.end();
});
}
function getCalcForm(req, resp, data) {
resp.writeHead(200, { "Content-Type": "text/html" });
getCalcHtml(req, resp, data);
}
function getHome(req, resp) {
resp.writeHead(200, { "Content-Type": "text/html" });
resp.write("<html><html><head><title>Home</title></head><body>Want to some calculation? Click <a href='/calc'>here</a></body></html>");
resp.end();
}
function get404(req, resp) {
resp.writeHead(404, "Resource Not Found", { "Content-Type": "text/html" });
resp.write("<html><html><head><title>404</title></head><body>404: Resource not found. Go to <a href='/'>Home</a></body></html>");
resp.end();
}
function get405(req, resp) {
resp.writeHead(405, "Method not supported", { "Content-Type": "text/html" });
resp.write("<html><html><head><title>405</title></head><body>405: Method not supported</body></html>");
resp.end();
}
http.createServer(function (req, resp) {
switch (req.method) {
case "GET":
if (req.url === "/") {
getHome(req, resp);
}
else if (req.url === "/calc") {
getCalcForm(req, resp);
}
else {
get404(req, resp);
}
break;
case "POST":
if (req.url === "/calc") {
var reqBody = '';
req.on('data', function (data) {
reqBody += data;
if (reqBody.length > 1e7) { //10MB
resp.writeHead(413, 'Request Entity Too Large', { 'Content-Type': 'text/html' });
resp.end('<!doctype html><html><head><title>413</title></head><body>413: Request Entity Too Large</body></html>');
}
});
req.on('end', function () {
var formData = qs.parse(reqBody);
getCalcForm(req, resp, formData);
});
}
else {
get404(req, resp);
}
break;
default:
get405(req, resp);
break;
}
}).listen(port);
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;
如果你从POST接收到JSON格式的数据。:
import http from 'http';
const hostname = '127.0.0.1';
const port = 3000;
const httpServer: http.Server = http.createServer((req: http.IncomingMessage, res:
http.ServerResponse) => {
if(req.method === 'POST') {
let body: string = '';
req.on('data',(chunck) => {
body += chunck;
});
req.on('end', () => {
const body = JSON.parse(body);
res.statusCode = 200;
res.end('OK post');
});
}
});
httpServer.listen(port, hostname, () => {
console.info(`Server started at port ${port}`);
})
如果你使用node- terrible,你可以这样做:
var formidable = require("formidable");
var form = new formidable.IncomingForm();
form.parse(request, function (err, fields) {
console.log(fields.parameter1);
console.log(fields.parameter2);
// ...
});