我正在尝试从表单输入console.log。但是,正在尝试在终端上打印的输入中,正文解析器显示“未定义”。我不确定我做错了什么。 请告诉我做错了什么。谢谢。
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}');
});
答案 0 :(得分:1)
如果您正在处理节点中的文件,bodyParser将无法正常工作。
您的表单需要以下属性
renderTodos(){
return this.props.reminder.map((item)=>{
if(this.state.filter === 'completed'){
if( item.completed){
return <li key={item.id}
style={{textDecoration: item.completed? 'line-through':'none'}}
onClick = {()=>{this.props.onToggle(item.id)}} >
<input type="checkbox" checked={item.completed} />
{item.text}
</li>
}
else null;
}
return <li key={item.id}
style={{textDecoration: item.completed? 'line-through':'none'}}
onClick = {()=>{this.props.onToggle(item.id)}} >
<input type="checkbox" checked={item.completed}/>
{item.text}
</li>
})}
}
render(){
return(
<div>
<ul>
{this.renderTodos()}
</ul>
<Filters
reminders={this.props.reminder}
filterState={this.getFilter}
/>
</div>
)
}
在节点中,您需要multer
<form action="/account/edit" method="post" enctype="multipart/form-data"></form>
var multer = require('multer');
&#13;
大部分代码都是检查目录。
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
}
}
这是我实际处理帖子的代码
const upload = multer({ fileFilter: imageFilter, storage: storage }).single("profile_pic");
&#13;
这些代码大部分是标准的,并且用multer记录。如果您有任何问题,我会查看https://github.com/expressjs/multer。
答案 1 :(得分:0)
您的表单是多部分的,因此req.body无法检索从HTML表单发送的数据。您需要使用Multer,其解释如下:https://www.npmjs.com/package/multer
总而言之,处理来自multer的请求。您需要为multer对象提供配置。这是一个代码示例,此代码在singleFileUpload中接收请求并运行上载功能。上载功能通过multer配置处理请求。如果要检索数据,则可以通过multer.diskStorage中的request函数访问数据。
让我知道是否要澄清。
`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);
});
}`