Currently unable to get a basic multer text form example working.
'use strict';
const express = require('express');
const app = express();
const PORT = 8077;
app.listen(PORT, () => {
console.info(`Started http://localhost:${PORT} (PID: ${process.pid})`);
const multer = require('multer');
const upload = multer();
app.post('/post', upload.none(), (req, res) => {
console.log("POST");
console.log(req.body);
});
postSomething();
});
async function postSomething() {
const fetch = require('node-fetch');
let res = await fetch('http://localhost:8077/post', {
method: 'POST',
credentials: 'include',
headers: {'Content-type': 'multipart/form-data; boundary=abcde12345' },
body: `--abcde12345
Content-Disposition: form-data; name="id"
Content-Type: text/plain
foo
--abcde12345--`
});
console.log(res.status);
}
What is the problem with parsing this body?
Error: Unexpected end of form
at Multipart._final (C:\projects\bar\node_modules\busboy\lib\types\multipart.js:588:17)
at callFinal (node:internal/streams/writable:696:27)
at prefinish (node:internal/streams/writable:725:7)
at finishMaybe (node:internal/streams/writable:735:5)
at Multipart.Writable.end (node:internal/streams/writable:633:5)
at IncomingMessage.onend (node:internal/streams/readable:693:10)
at Object.onceWrapper (node:events:627:28)
at IncomingMessage.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
CodePudding user response:
The solution is to use \r\n
instead of implicit line endings as well as ensuring that there is an empty line before each value.
'use strict';
const express = require('express');
const app = express();
const PORT = 8077;
app.listen(PORT, () => {
console.info(`Started http://localhost:${PORT} (PID: ${process.pid})`);
const multer = require('multer');
const upload = multer();
app.post('/post', upload.none(), (req, res) => {
console.log("POST");
console.log(req.body?.id);
});
postSomething();
});
async function postSomething() {
const fetch = require('node-fetch');
let res = await fetch('http://localhost:8077/post', {
method: 'POST',
credentials: 'include',
headers: {'Content-type': 'multipart/form-data; boundary=abcde12345' },
body: `--abcde12345\r\nContent-Disposition: form-data; name="id"\r\nContent-Type: text/plain\r\n\r\nfoo\r\n--abcde12345--`
});
console.log(res.status);
}
So basically my mistakes were:
- Not using CRLF
- Forgetting a newline before
foo
- Using the wrong boundary (the header has one
--
less than the body)
CodePudding user response:
use body-parser middleware for this issue and will resolve your problem
const bodyParser = require('body-parser')
// ...
app.use(bodyParser())