【发布时间】:2019-01-17 11:59:18
【问题描述】:
我有一些其他人编写的代码,它是一个 jquery 函数,它采用动态呈现的列表,并且在按钮单击时应该通过 express 将对象提交到 mongo 集合。
该功能在本地工作,在我推送到 heroku 后它对我有用。但是,一位同事一直无法让按钮单击工作,使用 google chrome 或 safari,页面只是刷新并且没有添加对象。我相信我已经重现了这个问题,但仅限于 MS Edge。
这是jquery函数:
function OnAddProxyClick() {
let proxies = [];
const checkboxes = $('.proxy-input:checked');
for (const checkbox of checkboxes) {
proxies.push({
proxyTitle: checkbox.getAttribute('data-title'),
proxyValue: checkbox.getAttribute('data-value'),
proxyUnit: checkbox.getAttribute('data-unit')
});
}
//fetch returns a promise, handle it with .then and check the response to do error handling
//otherwise if all goes well we should redirect
const url = window.location.pathname + '/proxies';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
body: JSON.stringify({ proxies: proxies })
}).then(res => {
if (res.ok) {
location.reload();
} else {
//show an error here if adding proxy doesn't work
console.log('The proxy wasnt added')
}
});
}
如果我删除 location.reload 并让页面挂起,正确的对象可以被 console.logged,但不会添加到集合中。
这是快递代码:
router.post("/:id/proxies", async (req, res) => {
let newProxies = [];
for (const proxy of req.body.proxies) {
newProxies.push({
proxyTitle: proxy.proxyTitle,
proxyValue: proxy.proxyValue,
proxyUnit: proxy.proxyUnit,
});
}
// Add every new proxy to the project proxies array
const query = { _id: req.params.id };
const update = { $addToSet: { proxies: { $each: newProxies } } };
const project = await Project.findById(query);
//make sure we don't add a duplicate
for (const newProxy of newProxies) {
let shouldPush = true;
for (const proxy of project.proxies) {
if (
proxy.proxyTitle == newProxy.proxyTitle &&
proxy.proxyValue == newProxy.proxyValue &&
proxy.proxyUnit == newProxy.proxyUnit
) {
shouldPush = false;
break;
}
}
if (shouldPush) {
// have tried awaiting this
project.proxies.push(newProxy);
}
}
await project.save();
res.end();
}
);
'update' 变量似乎可以检查 mongo 对象是否存在于集合中但未使用(我尝试使用它但没有帮助),我尝试在项目上使用 await。 proxies.push,这也不起作用。我可以在 Edge 工具中找到的唯一错误是与不匹配的标签有关,但这并不能解释为什么它在 chrome 中对我有用,但对我的同事却没有。
如何确保在页面重新加载之前对象已实际添加到集合中?
【问题讨论】: