【问题标题】:Redirecting to database table value重定向到数据库表值
【发布时间】:2017-02-24 11:53:01
【问题描述】:

我正在编写 URL 缩短器,但遇到了一些问题。

所以当用户发送请求时,比如 http://localhost:3000/1,我希望它重定向到存储在具有 ID 的列 original_url 下的 url 1 在我的数据库中。

这是我为实现此目的而编写的函数:

// :id will match anything after the / in the url, and set it as the req.params.id 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) {
      done();
      console.log(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 =" + req.params.id);
    console.log("successfully matched database id value to id value in url");

    console.log(req.query);
    res.redirect(req.query);
  });
});

问题是,在我匹配正确的 ID 后,我不知道如何将用户重定向到存储在我的列 original_url 中的 url,其中包含要重定向到的 url。

如何检索与输入的 ID 对应的 original_url 的值?

Here is my full code

【问题讨论】:

    标签: javascript node.js database postgresql


    【解决方案1】:

    假设您正在使用来自 npm (npm i --save pg) 的 node-postgres 包, 查询的结果以 result.rows 的形式提供。如果您找到单行,result.rows[0].original_url 可能会有您的重定向。此外,pg 包使用公共节点回调模式。

    client.query('SELECT * FROM items WHERE id = $1', [req.params.id], function (err, result) {
        if (err) throw err;
    
        console.log(result.rows[0]); // outputs: { original_url: 'http://mysite.dev' };
    }
    

    如果你使用的是 restify 服务器,你必须通过 next 来重定向。 Express 不需要。

    以restify为例:

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

    如果重定向 url 不包含协议(即 http),则重定向将相对于当前 url 路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多