我发布了包含multipart/form-data
enctype的表单数据。我使用了formiddable
nodejs middlerware,之前只适用于application/json
类型。
我发现 express.js 有一个名为require('body-parser');
的中间件可以达到同样的效果。
这是我的app.js
var Express = require('express');
var Multer = require('multer');
var BodyParser = require('body-parser');
var app = Express();
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: false}));
var storage = Multer.diskStorage({
destination: (req, file, callback) => {
callback(null, './uploads');
},
filename: (req, file, callback) => {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = Multer({storage: storage}).single('songUpload');
app.post('/artists', (req, resp) => {
var song = req.body //its empty, {}
console.log(req.body.album) // its undefined
console.dir(song)
upload(req, resp, (err) => {
if (err) {
return resp.end("Error uploading file, " + err);
}
resp.render("artists/profile", {artistName: "UPD : Radio for Dreams"});
});
})
表单视图
<form id="musicUpload" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="album">Album</label>
<input name="album"/>
<br/>
<label for="song"> Song </label>
<input name="email"/>
<br/>
<label for="songUpload"> Upload audio </label>
<input name="songUpload" type="file" multifile="multifile">
<br/>
<label for="tags"> Tags </label>
<input name="message"/>
<br/>
<input type="submit" value="Share to listeners">
</fieldset>
</form>
Content-Type:multipart/form-data
的http请求如下所示
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,en-GB;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:509
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryCSC5Po9i0QGe587Z
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/artists
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
而且,帖子数据是
但是,在服务器端,我无法使用express.js解析器获取发布的数据。它全是空的。
答案 0 :(得分:1)
您需要将multer
中间件调用添加到路由处理程序:
app.post('/artists', upload, (req, resp) =>