Created
January 2, 2019 05:03
-
-
Save ajmas/095061c9acf7a34be3731846b744b3d8 to your computer and use it in GitHub Desktop.
Allow express body-parser to deal with missing content-type headers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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