从 TinyURL 的缩短方法捕获响应时出错
Error capturing response from TinyURL's shorten method
我需要从 TinyUrl
库中捕获 shorten
方法的 return。我正在尝试将此 return 存储在 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);
时,正确显示了所需的 return,但未设置 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,
});
我需要从 TinyUrl
库中捕获 shorten
方法的 return。我正在尝试将此 return 存储在 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);
时,正确显示了所需的 return,但未设置 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,
});