我需要从 shorten
库中捕获 TinyUrl
方法的返回。我正在尝试将此返回值存储在 shortUrl
变量中,然后将其保存在数据库中,如下所示:
import TinyUrl from 'tinyurl';
let shortUrl = '';
TinyUrl.shorten(req.body.url, function (response, error) {
if (error) console.log(error);
console.log(response);
shortUrl = response;
});
// Tudo certo para CRIAR o Site
const { id, hits, url, short_url } = await Site.create({
hits: 0,
url: req.body.url,
short_url: shortUrl,
});
return res.json({
id,
hits,
url,
short_url,
});
查看 console.log(response);
时,正确显示了所需的返回值,但未设置 shortUrl
变量。我该怎么做 ?
最佳答案
我是这样实现的:
const shortUrl = await TinyUrl.shorten(req.body.url);
const { id, hits, url, short_url } = await Site.create({
hits: 0,
url: req.body.url,
short_url: shortUrl,
});
关于javascript - 从 TinyURL 的缩短方法捕获响应时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63581403/