简体   繁体   中英

What is the proper way to redirect http requests based on the content in database?

While running an express server, what is the proper way to redirect incoming requests?

I have two routes: POST and UPDATE. The POST route is used to create new item to database and UPDATE increases votes in the item.

I would like to use middleware(?) to redirect my requests based on db content:

  • if element with req.param does exist => redirect to UPDATE to handle upvotes

  • else create new element => redirect to POST to handle creation

I think a simple way of doing this could be:

const middleware = (req, res, next) => {
     req.param.name ? req.url = '/POST' : req.url = '/UPDATE' 
          next();
}
  

, Or you can redirect your request to other routes.

const middleware = (req, res, next) => {
     req.param.name ? res.redirect('/POST') : res.redirect(/UPDATE')
          next();
}

Also, you can make dynamic routes if you have many routes involved doing different things. You can check this: How to call an api from another api in expressjs?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM