node.js,在我的app.post请求中表达没有正文对象

时间:2017-03-22 15:36:16

标签: javascript node.js express

我有一个node.js和express的问题,我试图从一个来自html文件的帖子中获取信息,问题是,当我执行我的请求的console.log时,我没有任何信息在我的req.body里面。

我在app.post(“/ render_pdf”....)的开头做了一个console.log(req.body),我得到的只是一个空对象。

我不知道它是来自我的.html还是我的server.js,但我不明白问题的来源。我使用multer上传基于html选择的pdf,它正在工作..所以我没有任何解决方案。

我的HTML(有点像php):

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>ebook-stage</title>
  <link href="public/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

<?php
$pdo=new PDO('mysql:host=localhost; dbname=ebook-stage; charset=utf8',
    'root', '');
$statement=$pdo->prepare("SELECT * FROM publication");
$statement->execute();
?>

  <div class="jumbotron">
    <div class="container-fluid">
      <div class="row">
        <div class="col-md-3">
          <form method="POST" action="http://localhost:8090/create_pdf" enctype="multipart/form-data">
            <label for="extractor">Extracteur PDF</label>
            <br><select class="form-control" name="extractor" id="extractor">
              <option name="pdf2json" value="pdf2json">PDF2JSON</option>
              <option name="pdfextract" value="pdfextract">PDFEXTRACT</option>
              <option name="textract" value="textract">TEXTRACT</option>
            </select>
          <br><label for="file">Upload Pdf</label>
          <input id="file" type="file" name="file">
          <br><input type="submit" name="submit" id="submit" class="exec btn btn-success" value="Exécuter">
          </form>
        </div>
        <div class="col-md-3">
          <form method="POST" action="http://localhost:8090/render_pdf">
            <label for="require">PDF a afficher</label>
            <br><select class="form-control" name="require" id="require">
              <?php while ($rendername = $statement->fetchObject()):?>
                <option name="<?= $rendername->name ?>"><?= $rendername->name ?></option>
              <?php endwhile; ?>
          </select>
            <?php while ($rendername = $statement->fetchObject()):?>
            <input type="hidden" name="<?= $rendername->id ?>" id="id">
            <?php endwhile; ?>
            <br><input type="submit" name="envoi" id="envoi" class="exec btn btn-success" value="Afficher">
          </form>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

我的pdf-rest.js:

var mysql = require('mysql');
var bodyParser = require('body-parser');
var request = require('request');
var jsonParser = bodyParser.json();
var http = require('http');
var fs = require('fs');
var Promise = require('bluebird');
var multer  = require('multer');
var textract = require('textract');
var pdf_extract = require('pdf-extract');
var PDFParser = require("pdf2json");
var pdfParser = new PDFParser();
var inspect = require('eyes').inspector({maxLength:20000});
var optionsExtract = {
    type: 'ocr' // perform ocr to get the text within the scanned image
};
var express = require('express');

module.exports = function(app){

    function requireDB(){
        connection.connect();
        connection.query('SELECT * FROM publication WHERE id = 105', function(err, rows, fields){
            console.log(err);
            res.end(rows[0].id+rows[0].name);
        });
    }

    app.post('/render_pdf', jsonParser, function (req, res) {
        console.log(req);
        res.end('affichage pdf');
    });

    var destination = "uploads";
    app.post('/create_pdf', jsonParser, function (req, res) {
        console.log(req.body);
        var connection = mysql.createConnection({
            user: 'root',
            password: '',
            host: 'localhost',
            port: 3306,
            database: 'ebook-stage'
        });

        var filename = "" + Date.now() + ".pdf";
        var filePath = "C:\\wamp64\\www\\ebook-stage\\backend\\rest\\uploads\\" + filename;
        var storage = multer.diskStorage({
            destination: function (req, file, cb) {
                cb(null, destination);
            },
            filename: function (req, file, cb) {
                cb(null, filename);
            }
        });

        var upload = multer({storage: storage}).single('file');
        function uploadFile() {
            console.log('entering upload file');
            var uploadFilePromise = new Promise(function (resolve,reject) {
                upload(req, res, function (err) {
                    if (err) {
                        reject(err);
                        res.end('error uploading file')
                    }
                    else{
                        console.log('upload resolve');
                        res.end('pdf uploaded');
                        console.log(req.body);
                        resolve(req);
                    }
                });
            });
            return uploadFilePromise;
        }

        function insertDB(pdfObject) {

            connection.connect();
            var insertPublication = {name: pdfObject.originalFilename};
            new Promise(function (resolve, reject) {
                connection.query('INSERT INTO publication SET ?', insertPublication, function (err, res) {
                    if (err) {
                        reject(err);
                    }
                    else {
                        console.log('insertDB publication');
                        console.log(res);
                        resolve(res['insertId']);
                    }
                });
            }).then(function (pubId) {
                pdfObject.text.forEach(function (text) {
                    var insertContent = {type: 'TXT', content: text};
                    new Promise(function (resolve, reject) {
                        connection.query('INSERT INTO content SET ?', insertContent, function (err, res) {
                            if (err) {
                                console.log(err);
                                reject(err)
                            }
                            else {
                                console.log('insertDB content');
                                console.log(res);
                                resolve(res['insertId']);
                            }
                        });
                    }).then(function (insertBlock) {
                        var blockid = {contentid: insertBlock};
                        new Promise(function (resolve, reject) {
                            connection.query('INSERT INTO block SET ?', blockid, function (err, res) {
                                if (err) {
                                    console.log(err);
                                    reject(err);
                                }
                                else {
                                    console.log('insertDB block');
                                    console.log(res);
                                    resolve(res['insertId']);
                                }
                            });
                        }).then(function (blockId) {
                            var linkpublicationids = {blockid: blockId, publicationid: pubId};
                            connection.query('INSERT INTO linkpublication SET ?', linkpublicationids, function (err, res) {
                                if (err) {
                                    console.log(err);
                                    return err
                                }
                                else {
                                    console.log('insertDB linkpublication');
                                    console.log(res);
                                }
                            });
                        })
                    });
                });
            }).catch(function () {
                connection.end(function (err) {
                    console.log(err);
                })
            });
        }

        function textractPdf(originalFilename) {
                    console.log('TEXTRACT PDF');
                    var textBlockPromise = new Promise(function (resolve, reject){
                        textract.fromFileWithPath(filePath, function (error, text) {
                            var result = [{originalFilename: originalFilename}];

                            if (error) {
                                console.log('Text is not parsed');
                                reject(error);
                            }
                            else {
                                console.log('Text is parsed');
                                result[0].text = [];
                                result[0].text.push(text);
                                resolve(result[0]);
                                console.log('after resolve textract')
                            }
                        });
                    });
                    console.log('exiting textract');
                    return textBlockPromise;
                }

        function extractPdf(originalFilename) {
            console.log('EXTRACT PDF');
            var textBlockPromise = new Promise(function (resolve, reject){
                var result = [{originalFilename: originalFilename}];
                processor = pdf_extract(filePath, optionsExtract, function (err) {
                    if (err) {
                        console.log('error extract');
                        reject(err);
                    }
                });
                processor.on('complete', function (data) {
                    var resultsplited = data.text_pages[0].split('\n');
                    result[0].text = [];
                    resultsplited.forEach(function(text){
                        result[0].text.push(text);
                    });
                    resolve(result[0]);
                });
                processor.on('error', function (err) {
                    console.log('error extract');
                    inspect(err, 'error while extracting pages');
                    reject(err);
                });
            });
            return textBlockPromise;
        }

        function convertPdf2json(originalFilename){
            console.log('EXTRACT PDF2JSON');
            var textBlockPromise = new Promise(function (resolve, reject){
                var result = [{originalFilename: originalFilename}];
                result[0].text = [];
                pdfParser.on("pdfParser_dataError", function(errData){
                    reject(errData);
                });
                pdfParser.on("pdfParser_dataReady", function(pdfData){
                    pdfData.formImage.Pages.forEach(function(page){
                        page.Texts.forEach(function(text){
                            var textparsed = decodeURIComponent(text.R[0].T);
                            result[0].text.push(textparsed);
                        });
                    });
                    resolve(result[0]);
                });
                pdfParser.loadPDF(filePath);
            });
            return textBlockPromise
        }

        function selectExtractor(req){
            console.log(req.body.extractor);
            var extractorPromise = new Promise(function (resolve){
                if(req.body.extractor == 'textract'){
                    resolve (textractPdf(req.file.originalname));
                    console.log('extractor end');
                }
                else if(req.body.extractor == 'pdfextract'){
                    resolve(extractPdf(req.file.originalname));
                    console.log('extractor end');

                }
                else if (req.body.extractor == 'pdf2json'){
                    resolve(convertPdf2json(req.file.originalname));
                    console.log('extractor end');
                }
            });
            return extractorPromise;
        }
        uploadFile().then(selectExtractor).then(insertDB);
    });
};

我的server.js:

var express = require('express');

var app = express();

require('./pdf-rest.js')(app);

app.listen(8090);

2 个答案:

答案 0 :(得分:0)

只是尝试将服务器文件更新为实际使用req.body,我们需要将中间件注册到我们所有的路由。

   var express = require('express');
    var bodyParser = require('body-parser');

    app.use(bodyParser.urlencoded({ extended: false }))
    var app = express();

    require('./pdf-rest.js')(app);

    app.listen(8090);

答案 1 :(得分:0)

当你在表单中使用multipart/form-data时,正文解析器可能在这里没有帮助。见body-parser home page

  

由于它们复杂且通常较大,因此不能处理多部分主体。对于多部分机构,您可能对以下模块感兴趣:

我没有multer的经验,但尝试按照documentation中描述的那样使用它:

var upload = multer({ dest: 'uploads/' })

app.post('/create_pdf', upload.single('file'), function (req, res, next) {
  // req.file is the uploaded file
  // req.body will hold the text fields, if there were any 
})