从Nodejs中的请求中提取POST参数

时间:2014-06-08 15:30:19

标签: javascript node.js express http-post

我试图通过使用请求来获取变量postData中POST的参数 - (我使用了这个,因为这里有人建议 - How do I get the post request with express js?

在这里 - How to retrieve POST query parameters?

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);

并收到此错误 -

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)

我正在使用身体解析器,之前我在这里阅读了一些解决方案,它给了我相同的错误中间件丢失,我安装全局然后也得到了相同的错误,之后我读了关于json,所以我全局安装它

npm install -g json

也不起作用。然后我尝试添加依赖项 -

{
  "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"
  }
}

并运行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)

编辑** - 使用新的身体解析器模块的代码

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);

在这里我得到了

{}

在控制台中,这意味着body对象由于某种原因是空的。

2 个答案:

答案 0 :(得分:1)

使用Express 4,身体解析中间件(与其他先前内置的中间件一样)被提取到“body-parser”模块中。但是,这个新模块只处理JSON和urlencoded表单提交,而不是多部分。

如果您需要多部分支持,则需要使用connect-busboymulterconnect-multiparty之类的内容(connect-multiparty本质上是旧的Express bodyParser中间件)。

编辑:此外,textarea输入字段缺少name属性。这是必需的,否则该字段将不会与表单一起发送。

答案 1 :(得分:0)

使用express 4时,使用body-parser中间件获取参数。 Multipart有一个问题,即它会创建大量的临时文件。因此,最好尽可能避免使用它并直接使用上传服务。

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);
            }
        }
    });

然后只需将您的请求参数设为:

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