如何在Node.js中处理POST数据?
如何提取表单数据(如何在Node.js中处理POST数据?,node.js,http-post,Node.js,Http Post,如何提取表单数据(form[method=“post”]),以及从中的HTTPpost方法发送的文件上载 我读了文档,用谷歌搜索了一下,什么也没找到 function (request, response) { //request.post???? } 是否有库或黑客?如果您使用(Node.js的高性能、高级别web开发),您可以执行以下操作: HTML: <form method="post" action="/"> <input type="text" n
form[method=“post”]
),以及从中的HTTPpost
方法发送的文件上载
我读了文档,用谷歌搜索了一下,什么也没找到
function (request, response) {
//request.post????
}
是否有库或黑客?如果您使用(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>
fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
user: {
name: "John",
email: "john@example.com"
}
})
});
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!");
});
});
Node.js:(从Express v4.16.0开始)
Node.js:(对于Express,您可以使用以下模块:
现在,例如,如果您有一个名为age
的input
字段,您可以使用变量post
访问它:
console.log(post.age);
如果您不想像Express那样使用整个框架,但是您还需要不同类型的表单,包括上传,那么这可能是一个不错的选择
它列在中,如果有人试图淹没您的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
});
}
}
这是一个非常简单的无框架包装器,它基于此处发布的其他答案和文章:
var http = require('http');
var querystring = require('querystring');
function processPost(request, response, callback) {
var queryData = "";
if(typeof callback !== 'function') return null;
if(request.method == 'POST') {
request.on('data', function(data) {
queryData += data;
if(queryData.length > 1e6) {
queryData = "";
response.writeHead(413, {'Content-Type': 'text/plain'}).end();
request.connection.destroy();
}
});
request.on('end', function() {
request.post = querystring.parse(queryData);
callback();
});
} else {
response.writeHead(405, {'Content-Type': 'text/plain'});
response.end();
}
}
用法示例:
http.createServer(function(request, response) {
if(request.method == 'POST') {
processPost(request, response, function() {
console.log(request.post);
// Use request.post here
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
response.end();
});
} else {
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
response.end();
}
}).listen(8000);
如果您不想将数据与
数据
回调组合在一起,您可以像这样使用可读
回调:
// 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
});
http.createServer((request, response) => {
const chunks = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', () => {
const data = Buffer.concat(chunks);
console.log('Data: ', data);
})
}).listen(8080)
这种方法会修改传入的请求,但是一旦您完成响应,请求就会被垃圾收集,所以这应该不是问题
如果您害怕巨大的实体,一种高级方法是首先检查实体大小。如果您正在使用,在访问req.body之前,必须添加中间件bodyParser:
app.use(express.bodyParser());
然后你可以要求
req.body.user
如果您使用以下方法,您可以这样做: 如果您将数据编码为JSON,然后将其发送到Node.js,则会更干净
function (req, res) {
if (req.method == 'POST') {
var jsonString = '';
req.on('data', function (data) {
jsonString += data;
});
req.on('end', function () {
console.log(JSON.parse(jsonString));
});
}
}
您可以使用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);
})
任何想知道如何在不安装web框架的情况下完成这项琐碎任务的人,都可以在这里找到更多文档。我设法将其拼凑在一起。虽然还没有准备好生产,但它似乎可以工作
function handler(req, res) {
var POST = {};
if (req.method == 'POST') {
req.on('data', function(data) {
data = data.toString();
data = data.split('&');
for (var i = 0; i < data.length; i++) {
var _data = data[i].split("=");
POST[_data[0]] = _data[1];
}
console.log(POST);
})
}
}
函数处理程序(req、res){
var POST={};
如果(请求方法=='POST'){
请求开启(“数据”,功能(数据){
data=data.toString();
data=data.split('&');
对于(变量i=0;i
您可以在不使用express的情况下提取post参数
1:nmp安装多方
2:导入多方。asvar multiparty=require('multiparty');
3:`
4:HTML表单是
<form method=POST enctype=multipart/form-data>
<input type=text name=userfile1><br>
<input type=submit>
</form>
我希望这对你有用。谢谢。限制帖子大小避免淹没你的节点应用程序。
有一个很好的模块,适用于express和connect,可以帮助您根据大小和长度限制请求。我找到了一个视频,介绍了如何实现这一点: 它使用默认的“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);
var http=require(“http”);
var qs=要求(“查询字符串”);
var StringBuilder=require(“StringBuilder”);
var端口=9000;
函数getCalcHtml(请求、响应、数据){
var sb=新的StringBuilder({newline:“\r\n”});
某人加上一行(“”);
某人加上一行(“”);
某人加上一行(“”);
某人加上一行(“”);
某人加上一行(“”);
sb.追加行(“输入第一个编号:”);
if(data&&data.txtFirstNo){
sb.appendLine(“”,data.txtFirstNo);
}
否则{
某人加上一行(“”);
}
某人加上一行(“”);
某人加上一行(“”);
sb.追加行(“输入第二个编号:”);
if(data&&data.txtSecondNo){
sb.appendLine(“”,data.txtSecondNo);
}
否则{
某人加上一行(“”);
}
某人加上一行(“”);
某人加上一行(“”);
某人加上一行(“”);
某人加上一行(“”);
if(data&&data.txtFirstNo&&data.txtSecondNo){
var sum=parseInt(data.txtFirstNo)+parseInt(data.txtSecondNo);
某人加上一行(“”);
sb.appendLine(“Sum:{0}”,Sum);
某人加上一行(“”);
}
某人加上一行(“”);
某人加上一行(“”)
某人加上一行(“”);
某人加上一行(“”);
某人构建(功能(错误、结果){
分别写入(结果);
分别结束();
});
}
函数getCalcForm(请求、响应、数据){
分别写头(200,{“内容类型”:“text/html”});
getCalcHtml(请求、响应、数据);
}
函数getHome(请求、响应){
分别写头(200,{“内容类型”:“text/html”});
分别写入(“Home要进行一些计算吗?单击”);
分别结束();
}
功能get404(请求、响应){
响应写头(404,“未找到资源”,{“内容类型”:“text/html”});
分别写入(“404404:未找到资源。转到”);
分别结束();
}
功能get405(请求、响应){
响应写头(405,“不支持方法”,{“内容类型”:“text/html”});
分别写入(“405405:不支持方法”);
分别结束();
}
http.createServer(函数(req,resp){
开关(请求方法){
案例“GET”:
如果(请求url==“/”){
回家(请求、响应);
}
否则如果(req.url==“/calc”){
getCalcForm(请求、响应);
}
否则{
get404(请求、响应);
}
打破
案例“职位”:
如果(请求url==“/calc”){
弗吉尼亚州
<form method=POST enctype=multipart/form-data>
<input type=text name=userfile1><br>
<input type=submit>
</form>
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);
var multipart = require('multipart');
multipart.parse(req)
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);
<input type="text" name="user[name]" value="MyName">
<input type="text" name="user[email]" value="myemail@somewherefarfar.com">
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.
});
}
}
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!");
});
});
const http = require('http');
http.createServer((req, res) => {
if (req.method == 'POST') {
whole = ''
req.on('data', (chunk) => {
# consider adding size limit here
whole += chunk.toString()
})
req.on('end', () => {
console.log(whole)
res.writeHead(200, 'OK', {'Content-Type': 'text/html'})
res.end('Data received.')
})
}
}).listen(8080)
http.createServer((request, response) => {
console.log('Now we have a http message with headers but no data yet.');
request.on('data', chunk => {
console.log('A chunk of data has arrived: ', chunk);
});
request.on('end', () => {
console.log('No more data');
})
}).listen(8080)
http.createServer((request, response) => {
const chunks = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', () => {
const data = Buffer.concat(chunks);
console.log('Data: ', data);
})
}).listen(8080)
const http = require('http');
const concat = require('concat-stream');
http.createServer((request, response) => {
concat(request, data => {
console.log('Data: ', data);
});
}).listen(8080)
const http = require('http');
const concat = require('concat-stream');
const qs = require('querystring');
http.createServer((request, response) => {
concat(request, buffer => {
const data = qs.parse(buffer.toString());
console.log('Data: ', data);
});
}).listen(8080)
http.createServer((request, response) => {
request.pipe(fs.createWriteStream('./request'));
}).listen(8080)
limitedStream = request.pipe(meter(1e7));
limitedStream.on('data', ...);
limitedStream.on('end', ...);
request.pipe(meter(1e7)).pipe(createWriteStream(...));
concat(request.pipe(meter(1e7)), ...);
var bodyParser = require('body-parser');
app.use(bodyParser.json())
app.use(bodyParser.json())
app.use(bodyParser.json())
app.use('/user',user);
var postdata = req.body;
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire request body stored in it as a string
});
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)
})
var request = require('request');
function getData() {
var options = {
url: 'https://example.com',
headers: {
'Content-Type': 'application/json'
}
};
return new Promise(function (resolve, reject) {
var responseData;
var req = request.post(options, (err, res, body) => {
if (err) {
console.log(err);
reject(err);
} else {
console.log("Responce Data", JSON.parse(body));
responseData = body;
resolve(responseData);
}
});
});
}
var loginDetails = {
username : request.body.username,
password : request.body.password
};
app.use(express.urlencoded( {extended: true} ))
console.log(req.body) // object
require('url').parse(req.url, true).query.name
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}`);
})