Reputation: 91
I am trying to download a file from the folder using nodejs. Everything works fine while using get method. But when i am trying to send file name as parameter in post method it shows "undefined".
var download =req.body.download;
app.post("/hi", function (req, res)
{
res.download("./uploads/"+download+"");
});
download is my parameter where i will pass file name
Upvotes: 0
Views: 2035
Reputation: 1339
You should use middle-ware body-parser
to parse parameters from request body and get it inside scope of your POST handler. To install body-parser module:
npm install body-parser --save
Update your code like below:
const express = require('express')
const app = express()
const bodyParser = require("body-parser");
//Here we are configuring express to use body-parser as middle-ware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post("/hi", function (req, res) {
var download = req.body.download;
res.download("./uploads/"+download+"");
});
And make a call to POST /hi
with body json:
{
"download": "test"
}
UPDATED:
From Express 3, body-parser
middleware is attached (built-in) in express. So don't need to install it any more, just need to declare using module as code below:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
For reference: Express middleware
Upvotes: 5
Reputation: 1
Or you could pass params like this:
app.post("/hi/:download", function (req, res) {
var download = req.params.download;
res.download("./uploads/"+download+"");
});
And it doesn't even have to be a POST request anymore, you can just use a GET request. Also you can ditch body-parser with this method.
Upvotes: 0