这有点奇怪,但我想不出更好的方法来完成它。
首先,这是我的代码:
首先获取视图的路由器
router.get('/', function(req, res, next) {
Account.findOne(
{
_id: req.user._id,
},
function(err, acc) {
if (err) {
console.log(err);
}
// console.log(acc.websites);
res.render('reports/index', {
title: 'Reports!',
websites: acc.websites,
user: req.user,
});
}
);
});
观点:
<% include ./../partials/header.ejs %>
<h1 class="text-center">This is your report page</h1>
<form method="post">
<% for(let i=0; i<websites.length; i++){ let website = websites[i]; %>
<fieldset>
<label for="website<%=i%>" class="col-sm-2">Website <%=i+1%></label>
<input name="website<%=i%>" id="website<%=i%>" value="<%=website%>" type="text" />
</fieldset>
<% } %>
<a href="/report/<%= %>" class="btn btn-primary col-sm-offset-2">Generate report</a>
</form>
<% include ./../partials/footer.ejs %>
路由器,点击后应该启动。
router.get('/reports', function(req, res, next) {
if (req.user.isPremium == false) {
// Free user - Single report
var builtWithCall = `https://api.builtwith.com/free1/api.json?KEY=00000000-0000-0000-0000-000000000000&LOOKUP=${website}`;
let website = req.body.website0;
console.log(website);
}
});
工作原理:控制器找到该帐户,从其内部抓取一个数组,并将其发送到视图。视图将其打印出来并允许对值进行一些更改。
现在问题就出现了。我需要将新值收集到一个数组中并将其发送到下一个路由器,然后使用它们来调用一堆API并打印出数据。如何收集阵列并将其传递给控制器?另外,我应该使用GET还是POST?
答案 0 :(得分:1)
根据您的逻辑,name
属性将具有以下格式:name=website[0...n]
。考虑到这一点,我们可以过滤掉密钥,将所有website[n]
收集到您要搜索的数组中:
const example = {
website0: 'example',
website1: 'example',
website2: 'example',
website3: 'example',
shouldBeIgnored: 'ignoreMe',
ignore: 'shouldIgnore'
}
const websites = Object.keys(example).filter(key => key.startsWith('website'))
console.log(websites)
所以你的控制者可以是:
router.get('/reports', (req, res, next) => {
if (!req.user.isPremium) {
// Free user - Single report
const builtWithCall = `https://api.builtwith.com/free1/api.json?KEY=00000000-0000-0000-0000-000000000000&LOOKUP=${website}`;
const websites = Object.keys(req.body).filter(key => key.startsWith('website'));
console.log(websites);
}
});