Home > Blockchain >  Is there a way to 'set' a parameter in express routes from server?
Is there a way to 'set' a parameter in express routes from server?

Time:07-13

My app.post('/userSignUp') retrieves user id from the database, after which I want to set it like this /user/432874 from server itself. And then redirect it to route /user/432874. so far I'm setting it like this /user/ userid but running into error when trying to do a get request on /user/ userid. Why does this not work? Is there a way to do this?

Below is an example:

const userId;

app.post('/userSignUp', (req, resp, next) => {

  const HashQuery = {
      text: 'select * from users where session_id = $1',
      values: [req.cookies.hash_from_its_an_app]
  }

  client.query(HashQuery, (err, res) => {
      res.rows.map((i) => {
          userId = i.user_id;
      });
    resp.redirect('/user/'  userId); // the browser stops here and doesn't go forward with GET
  }

}


app.get('/user/'   userId, (req, res) => {

    res.render('index');

});

error on the browser is this:

Request URL: http://localhost:3000/user/10
Request Method: GET
Status Code: 404 Not Found
Remote Address: [::1]:3000
Referrer Policy: strict-origin-when-cross-origin

CodePudding user response:

Change user endpoint to,

app.get('/user/:userId', (req, res) => {

//Get userId value by `req.params.userId`
   ...

});
  • Related