user3335607 user3335607 - 4 months ago 25
Javascript Question

Redirecting to database table value

I'm writing a URL shortener but having some issues.

So when the user sends a request, say http://localhost:3000/1, I want it to redirect to the url stored under the column original_url that has the ID of 1 in my database.

Here is the function I wrote to achieve this:

// :id will match anything after the / in the url, and set it as the value
app.get('/:id', function (req, res) {
console.log("hi you're about to match url id to database id");
//get a prostgres client from the connection pool
pg.connect(connectionString, (err, client, done) => {
//handle connection errors
if (err) {
return res.status(500).json({ success: false, data: err });
//match id in database to id from query in url
const query = client.query("SELECT * FROM items WHERE id =" +;
console.log("successfully matched database id value to id value in url");


The problem is, after I match the correct ID, I don't know how to redirect the user to the url stored in my column original_url which contains the url to re-direct to.

How can I retrieve the value of original_url that corresponds to the entered ID?

Here is my full code


Assuming you are using node-postgres package from npm (npm i --save pg), the results of a query are available as result.rows. If you are finding a single row, result.rows[0].original_url would presumably have your redirect. Also, the pg package uses the common node callback pattern.

client.query('SELECT * FROM items WHERE id = $1', [], function (err, result) {
    if (err) throw err;

    console.log(result.rows[0]); // outputs: { original_url: '' };

If you are using restify server, you have to pass next to redirect. Express does not require that.

For example with restify:

app.get('/:id', function (req, res, next) {
  res.redirect(url, next);

If the redirect url does not include a protocol (i.e. http), then the redirect will be relative to the current url path.