作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个链接缩短器应用程序。这是 Express.js 的 POST 函数。我想发送一个包含新 url 和数据库中当前文档数的文档。这主要是为了确保每个网站都与一个唯一的短号码相关联。
app.post('/api/shorturl/new', (req, res) => {
var body = _.pick(req.body, ['url']); // url attached to body.url with lodash
Link.find({}).exec((err, res) => { // Link is a mongoose model
var count = res.length;
var newSite = new Link({ website: body.url, count });
newSite.save((err) => {
if (err) console.log(err);
})
res.send(newSite);
});
});
当程序到达 res.send(newSite) 时,控制台显示 res.send 不是一个函数。这是因为它在 promise 范围内,但我不确定如何将其取出并保持代码正常运行。如何获得要发送的响应?
谢谢!
最佳答案
您需要的不是res
。它被内部回调参数覆盖。您需要将内部 res
重命名为 _res
例如:
app.post('/api/shorturl/new', (req, res) => {
var body = _.pick(req.body, ['url']); // url attached to body.url with lodash
Link.find({}).exec((err, _res) => { // Link is a mongoose model
var count = _res.length;
var newSite = new Link({ website: body.url, count });
newSite.save((err) => {
if (err) console.log(err);
})
res.send(newSite);
});
});
关于javascript - 我如何在 node.js 的 promise 中重新发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857242/
我是一名优秀的程序员,十分优秀!