Reputation: 1200
I'm trying to extract data from a request (in this case a POST
) and am having trouble. I'm doing so using the body-parser
module. Below is a portion of my code (note I am using ES6 syntax):
let bodyParser = require('body-parser')
var urlEncodedParser = bodyParser.urlEncoded({extended: true})
app.post('*', setFileMeta, setDirDetails, urlEncodedParser, (req, res, next) => {
async ()=> {
if (!req.stat) return res.send(405, 'File does not exist')
if (req.isDir) return res.send(405, 'Path is a directory') // This is an advanced case
await fs.promise.truncate(req.filePath, 0)
req.pipe(fs.createWriteStream(req.filePath)) // Filepath is a file
// This below line is where I need the body
sendToClients('update', req.url, 'file', req.body, Date.now())
res.end()
}().catch(next)
})
For the actual extraction of the data using body-parser
, urlEncoded
is the only way I was able to successfully do it (the data is just a string for now), and it's giving me in the format {content: ''}
where content is the actual string I'm using. This isn't ideal but it works in this simple. However, this is breaking the createWriteStream(req.filePath)
as seen above - the file is created, but there is no content.
There must be something obvious that I'm doing incorrectly, as I'm new to Node and Express. Since I wrote the majority of this with the help of an instructional video, my gut tells me it's the body extraction part since I'm doing that on my own.
Upvotes: 0
Views: 110
Reputation: 203231
body-parser
exhausts (fully reads) the request stream in order to parse the incoming parameters, so there's no data left in the request stream to write to your file.
It seems to me that you're trying to implement file uploads. In that case, you probably want to use a module like multer
instead of body-parser
.
Upvotes: 2