问题
I have a simple form:
<form method="post" action="/test">
<input type="hidden" name="arr[]" value="val1">
<input type="hidden" name="arr[]" value="val2">
<input type="hidden" name="arr[]" value="val3">
<input type="submit" value="Submit">
</form>
With the controller:
//...
server.post('/test', function(req, res) {
res.json(req.body);
});
//...
This returns fine with:
{
arr: [
"val1",
"val2",
"val3"
]
}
However, when I change the enctype to multipart/formdata
<form method="post" action="/test" enctype="multipart/form-data">
<input type="hidden" name="arr[]" value="val1">
<input type="hidden" name="arr[]" value="val2">
<input type="hidden" name="arr[]" value="val3">
<input type="submit" value="Submit">
</form>
The server now responds with:
{
arr[]: "val3"
}
What's the issue? Is there some kind of configuration I need?
In case you're wondering, I'm also sending a file, that why I need the multipart/form-data
.
回答1:
It's probably related to the use of body-parser (especially the urlencoded
method) which, by default, works on requests with the media-type application/x-www-form-urlencoded
only.
Your main application module probably has some lines like these:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
I suppose, you could just add the following to have requests of type multipart/form-data
parsed as well:
app.use(bodyParser.urlencoded({
type: 'multipart/form-data'
}));
来源:https://stackoverflow.com/questions/23674208/multipart-form-data-with-arrays