【发布时间】: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 的值?
【问题讨论】:
标签: javascript node.js database postgresql