node.jsbody偏好器无法检索表单输入



我正在尝试启用表单中的输入。但是,对于我试图在终端上打印的输入,身体较好的人显示"未定义"。我不确定我做了什么不正确。请告知我做错了什么。谢谢。

html表单

<html>
<header>
    <link rel="stylesheet" type="text/css" href="css/form.css">
</header>
<body>
<form id="form" class="topBefore" action="/form" method="post" enctype="multipart/form-data">
              <input id="name" name="name" type="text" placeholder="NAME">
              <input id="email" name="email" type="text" placeholder="E-MAIL">
              <textarea id="message" name ="message" type="text" placeholder="MESSAGE"></textarea>
              <input type="file" name="upload" multiple>
      <input id="submit" type="submit" value="GO!">  
    </form>
</body>
</html>

app.js

// port and modules
var port = 3000;
var express = require('express');
var http = require('http');
var path = require('path');
var formidable = require('formidable');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var fs = require('fs');
var app = express();
// static resource folder (public)
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/form', function(req, res){
    res.sendFile(__dirname + "/public/form.html");
});
app.post('/form', function(req, res)
{   //get form input
    var name = req.body.name;
    var email = req.body.email;  
    var message = req.body.message;
    console.log(req.body.name);
    //upload file and save to directory
    var form = new formidable.IncomingForm();
    form.parse(req);  
    //set upload path
    form.on('fileBegin', function (name, file){
        file.path = __dirname + '/public/icons/' + file.name;
        console.log(file.path);
    });
    //upload process
    form.on('file', function (name, file){
        console.log('Uploaded ' + file.name);
    });
    // redirect to home page after form submission
    res.redirect('/');
});
// connect to server and listen port
// index.html will be home page
http.createServer(app).listen(port, function(){
    console.log("{ server connection : success }");
});
//Database setup
mongoose.connect('mongodb://localhost/mydb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('{ database connection : success}');
});

如果您正在使用节点中的文件,则BodyParser将无法使用。

您的表格需要以下属性

<form action="/account/edit" method="post" enctype="multipart/form-data"></form>

在节点中您需要Multer

var multer = require('multer');

// this is a simple reqex filter to check the ext
const imageFilter = (req, file, cb) => {
  let regex = new RegExp(/.(jpg|jpeg|png|gif)$/, "i");
  // return error
  if (!file.originalname.match(regex)) {
    return cb(new Error('Only image files are allowed!'), false);
  }
  cb(null, true);
};
// define the destination
var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    pathName = `photos/users/${req.user.dataValues.userid}`;
    var p = mkdirSync(pathName) // checks if photos/users exist
    if (p === false) {
      cb(true, null) // path does not exist
    } else {
      cb(null, pathName) // path exist
    }
  },
  filename: function(req, file, cb) {
    let regex = new RegExp(/.(jpg|jpeg|png|gif|bmp)$/, "i"); 
    let filename = file.originalname;
    let ext_arr = filename.match(regex);
    let ext_str = ext_arr[0]; // get ext
    cb(null, `${Date.now()}${ext_str}`); // file name is date.ext
  }
})
// if no directory, make directory
const mkdirSync = (dirPath) => {
  try {
    fs.mkdirSync(dirPath) // try it without making anything
  } catch (err) {
    if (err.code !== 'EEXIST') {
      fs.mkdirSync("photos/users") // make directory
      try {
        fs.mkdirSync(dirPath) // try it now that users directory is made
      } catch (err) {
        if (err.code !== 'EEXIST') {
          return false;
        }
      }
    }
  }
}
// makes the directory
const checkUserdirSync = (dirPath) => {
  try {
    fs.mkdirSync(dirPath)
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
}

大部分代码是检查目录。

multer 不会为您创建目录。

然后您需要将这些功能绑定到对象

您必须告诉它字段名称才能寻找

const upload = multer({ fileFilter: imageFilter, storage: storage }).single("profile_pic");

这是我实际处理帖子的代码

// saves file to system
function handleProfilePictureUpload(req, res, next) {
  upload(req, res, function(err) {
    if (err) req["file"] = false;
    if (!req["file"]) req["file"] = false;
    next();
  })
}

此代码大部分是标准的,并记录在Multer中。如果您有任何问题,我会检查https://github.com/expressjs/multer。

您的表单是多部分,因此req.body无法检索从HTML表单发送的数据。您需要使用Multer,请在此处解释:https://www.npmjs.com/package/multer

总而言之,以处理Multer的请求。您需要向Multer对象提供配置。这是一个代码示例,此代码将请求以singlefileupload为单位并运行上传函数。上载函数通过Multer配置处理请求。如果要检索数据,则可以通过multer.diskstorage中的请求函数访问它。

让我知道您是否想要澄清。

`var storage = multer.diskStorage({
   destination: function(req, file, cb) {
   cb(null, "public/uploaded_files");
   },
   filename: function(req, file, cb) {
    cb(null, req.files[0].fieldname);
   }
 });
var upload = multer({ storage: storage }).any();
function singleFileUpload(req, res) {
upload(req, res, err => {
 if (err instanceof multer.MulterError) {
   return res.status(500).json(err);
  } else if (err) {
   return res.status(500).json(err);
  }
 return res.status(200).send(req.file);
});
}`

最新更新