Send variable from post request to a simple middleware with NodeJs
Send variable from post request to a simple middleware with NodeJs
I have a this app.post :
app.post('/upload', upload.single('file'), (req, res,next) => {
let file = req.file.path;
let var1= path.basename(file,path.extname(file));
req.var1=var1;
console.log("le nom du fichier est : " + req.var1);
next();
})
Now i want to send this var1 to this middleware function because i am working with react and i want to dispatch it with ComponentDidMount but i get always undefined :
function last(req,res,next){
console.log(req.var1);
let results={
first:req.var1,
others:'req.var2'
}
res.send(results);
}
app.post('/Convert',last);
How can I resolve this ?
last
post
where i shall use res.locals ? I put it in the app.post but no way it doesn't resolve the problem
– khalfallah asma
Jun 29 at 11:31
I'm suggesting you replace
req.var1 = var1
with res.locals.var1 = var1
and then when fetching back out the result you can use first: res.locals.var1
. By all accounts it shouldn't matter, adding properties to the request object should do the same thing, it's just res.locals
is a mechanism already in place for this type of thing (moreso if you want to render data into a view). If neither works then it sounds like your middleware setup is wrong, you'd need to show more code.– James
Jun 29 at 11:37
req.var1 = var1
res.locals.var1 = var1
first: res.locals.var1
res.locals
Thank u James , i appreciate your help . It doesn't work but maybe i find another solution thnxx a lot
– khalfallah asma
2 days ago
The point I am making is both of these approaches should work, the fact they aren't suggests to me it's a problem with how you've setup your middleware - if you show this code then perhaps I could help further
– James
2 days ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Where in the request chain is the
last
middleware attached? Presumably after thepost
? FWIW I would say res.locals would be a better fit here.– James
Jun 29 at 9:57