[Fixed] node – How to get POST request params and then redirect user in express

Issue

I had this issue while I was trying to setup a post endpoint for my nodejs cli script that is using express to manage requests

        app.use( express.static( path.format({dir: __dirname, base: 'client/dist'})) );
        app.use( express.json() );

        app.get('/:uid', (req, res) => res.sendFile(path.format({dir: __dirname, base: 'client/dist/index.html'})) );        

        app.listen(this.port, async () => {
            console.log(`Server started at: http://localhost:${this.port}`);
        });

I’m using express 4.17.1 so it’s not needed to install bodyParser. How I will get the data posted from my vue front end, process them and then redirect user?

app.post('/action', (req, res) => {   
  // how I can get the passed params here and redirect user?
});

Solution

From what you have it’s pretty simple :

app.post('/action', (req, res) => {   
  // how I can get the passed params here and redirect user?
  console.log(req.body)// give you the passed parameter in post request thanks to app.use( express.json() );
  res.redirect('http://google.com');
});

Leave a Reply

(*) Required, Your email will not be published