简体   繁体   English

从Node.js中的请求中提取POST参数

[英]Extracting POST parameters from request in Nodejs

I am trying to get parameters from a POST in the variable postData by using the request by - ( i used this because it was suggested here - How do I get the post request with express js? ) 我试图通过使用-(我使用了这个,因为在这里建议-因为我如何使用express js获取发布请求? )从变量postData中的POST获取参数

and here - How to retrieve POST query parameters? 在这里- 如何检索POST查询参数?

var express = require('express');
var app = express();
var fs = require('fs');
var json = require('json');
app.use(express.json());       // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies

app.post('/shrib/:file/:data',function(req,res){
    var fileName = req.params.file;
    var data = req.params.data;
    req.on('data',function(data){ body+=data; } );
    req.on('end' ,function(){
        var postData = qs.parse(body);
        var writeStream = fs.createWriteStream(fileName);
        var postData = req.body.text;
        if(postData)
            console.log(postData);
        else    
            console.log("failed miserably");
        res.write(200);
        res.end();
    });
});
app.get('/shrib/:file',function(req,res){   
    var fileName = req.params.file;
    if(fileName != ''){
        var readStream = fs.createReadStream(fileName);
        var content;
        readStream.on('data',function(chunk){
            content+=chunk.toString();
            console.log(content);
        });
        readStream.on('end',function(){
            res.writeHead(200,{"Content-Type":"text/html"});
            res.write("<form id=\"submitForm\" method=\"POST\">");
            res.write("<textarea id=\"text\"rows=50 cols=50 >");
            console.log(content);
            if(content)
                res.write(content.toString());
            res.write("</textarea>");
            res.write("<input type=\"submit\" value=\"submit\" />");
            res.write("</form>");
            res.write("<script>");
            res.write("var windowLocation = location.href;");
            res.write("document.getElementById(\"submitForm\").action=windowLocation + \'/data\';");
            res.write("</script>");
            res.end();
        });
    }else{
        res.writeHead(200);
        res.write("invalid/empty path name"); 
    }
});
app.listen(8080);

and got this error - 并收到此错误-

Error: Most middleware (like json) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
    at Function.Object.defineProperty.get (/home/unknown/public_html/node/node_modules/express/lib/express.js:89:13)

I was using body parser before which i read in some solutions here and it gave me the same error middleware missing, i installed it globally then also got the same error and after that i read about json , so i installed it globally using 我使用的是body解析器,在此之前我在这里阅读了一些解决方案,它给了我相同的错误中间件,我在全局安装了它,然后又遇到了同样的错误,然后我读到了json,因此我使用

npm install -g json

did not work, then too. 也没有用 then i tried adding the dependancies - 然后我尝试添加依赖项-

{
  "name": "express_shrib.js",
  "version": "0.0.1",
  "description": "Creating Shrib Using Express",
  "main": "express_shrib.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/iamdeadman/nodejs.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/iamdeadman/nodejs/issues"
  },
  "homepage": "https://github.com/iamdeadman/nodejs",
  "dependencies": {
    "express": ">= 1.2.0",
    "json": ">= 9.0.0"
  }
}

and ran npm install still the same error - 并运行npm install仍然相同的错误-

Error: Most middleware (like json) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
    at Function.Object.defineProperty.get (/home/unknown/public_html/node/node_modules/express/lib/express.js:89:13)

Edit** - Code with the new body-parser module 编辑**-使用新的body-parser模块进行编码

var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
app.use(bodyParser());
app.post('/shrib/:file/:data',function(req,res){
    var fileName = req.params.file;
    var data = req.params.data;
    req.on('data',function(data){ body+=data; } );
    req.on('end' ,function(){
        var postData = req.body;
        var writeStream = fs.createWriteStream(fileName);
        if(postData)
            console.log(postData);
        else{   
            console.log("failed miserably");
            console.log(postData);
        }
        res.writeHead(200);
        res.end();
    });
});
app.get('/shrib/:file',function(req,res){   
    var fileName = req.params.file;
    if(fileName != ''){
        var readStream = fs.createReadStream(fileName);
        var content;
        readStream.on('data',function(chunk){
            content+=chunk.toString();
            console.log(content);
        });
        readStream.on('end',function(){
            res.writeHead(200,{"Content-Type":"text/html"});
            res.write("<form id=\"submitForm\" method=\"POST\">");
            res.write("<textarea id=\"text\"rows=50 cols=50 >");
            console.log(content);
            if(content)
                res.write(content.toString());
            res.write("</textarea>");
            res.write("<input type=\"submit\" value=\"submit\" />");
            res.write("</form>");
            res.write("<script>");
            res.write("var windowLocation = location.href;");
            res.write("document.getElementById(\"submitForm\").action=windowLocation + \'/data\';");
            res.write("</script>");
            res.end();
        });
    }else{
        res.writeHead(200);
        res.write("invalid/empty path name"); 
    }
});
app.listen(8080);

and here i get 我在这里

{}

in the console which means that the body object is empty for some reason. 在控制台中,这意味着主体对象出于某种原因为空。

With Express 4, the body parsing middleware (like other previously built-in middleware) was extracted out into the 'body-parser' module. 使用Express 4,主体解析中间件(就像其他以前内置的中间件一样)被提取到“ body-parser”模块中。 However, this new module only handles JSON and urlencoded form submissions, not multipart. 但是,此新模块仅处理JSON和urlencoded表单提交,而不处理多部分内容。

If you need multipart support, you'd need to use something like connect-busboy or multer or connect-multiparty (connect-multiparty is essentially the old Express bodyParser middleware). 如果需要多部分支持,则需要使用诸如connect- busboymulterconnect-multiparty之类的东西 (connect-multiparty本质上是旧的Express bodyParser中间件)。

EDIT: Also, the name attribute is missing for the textarea input field. 编辑:此外,textarea输入字段缺少name属性。 This is required, otherwise the field will not be sent with the form. 这是必需的,否则该字段将不会与表格一起发送。

When using express 4 use body-parser middleware to get parameters. 使用Express 4时,请使用body解析器中间件获取参数。 Multipart has issue that it creates loads of temp files. Multipart具有创建临时文件负载的问题。 So its better to avoid it whenever possible and use upload services directly. 因此,最好避免在可能的情况下直接使用上传服务。

app.use(function (req, res, next) {
        var urlParser = require('url');
        var url = urlParser.parse(req.url, true);
        if (url.pathname == "/rest/file/upload") {
            next();
        } else {
            var contentType = req.header("content-type");
            if (contentType && contentType.indexOf("application/json") != -1) {
                bodyParser.json({limit: 1024 * 1024 * 10})(req, res, next);
            } else {
                bodyParser.urlencoded({ extended: true, limit: 1024 * 1024 * 10})(req, res, next);
            }
        }
    });

then just get your request parameter as : 然后只需将您的请求参数获取为:

console.log(req.param("parameter-name"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM