Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Allow express body-parser to deal with missing content-type headers
// I was dealing with such an issue, where there was no content-type
// curl --upload-file '/Users/myuser/Movies/VID-20171025.mp4' -H http://localhost:3000/api/upload/path/to/myfile.xyz
const bodyParser = require('body-parser');
function req(req, res, next) {
const fileName = req.params.name;
if (Buffer.isBuffer(req.body)) {
fs.writeFileAsync("/tmp/" + fileName, req.body)
.then(() => {
console.log("The file was saved!");
})
.catch((err) => {
next(err);
});
} else {
console.log('body is not a buffer');
}
}
function initEndpoints (app) {
const rawParser = () => {
const parse = bodyParser.raw({ limit: '20mb' });
return function (req, res, next) {
if (!req.headers['content-type']) {
req.headers['content-type'] = 'application/octet-stream';
}
parse(req, res, next);
}
};
app.put('/api/upload/*/:name', rawParser(), this.uploadRaw.bind(this));
}
// alternatively, where you want to treat this as an error:
function initEndpoints (app) {
const rawParser = () => {
const parse = bodyParser.raw({ limit: '20mb' });
return function (req, res, next) {
if (!req.headers['content-type']) {
throw new Error('Missing content-type header');
}
parse(req, res, next);
}
};
app.put('/api/upload/*/:name', rawParser(), this.uploadRaw.bind(this));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.