我有这个获取请求,我接受它
// Server side
exports.redirect = async (req, res, next) => {
//res.status(403)
res.json({ Error: 'Plase try again' })
res.redirect('/signup')
}
// Client side
fetch('/redirect', {
credentials: "same-origin",
mode: "same-origin",
method: 'POST',
//redirect: 'follow',
headers: {
"Authorization": `Bearer ${jwt}`,
"Content-Type": "application/json"
},
body: JSON.stringify(inputJSON)
})
.then(resp => {
console.log(resp.url)
return Promise.all([resp.json()])
}
).then(data => {
console.log(data);
let jsonData = data[0]
let div = document.querySelector(".form-group");
div.insertAdjacentHTML('afterend', `<div id="response">${jsonData.Error}</div>`)
//setTimeout(windows.location = data.url, 5000);
})
.catch((error) => {
console.error(error);
}).catch(err => {
if (err === "server") return
console.log(err)
})
}
})
对于一般情况下,当您想将某些东西从上层传递.then
到下层时,您就快到了,您只需要将resp.url
加到Promise.all
您已有的数组中:
.then(resp => {
return Promise.all([resp.json(), resp.url])
}
).then(([data, url]) => {
const div = document.querySelector(".form-group");
div.insertAdjacentHTML('afterend', `<div id="response">${data.Error}</div>`);
setTimeout(() => window.location = url, 5000);
})
但它没有多大意义,既具有响应.json()
和重定向-选择一个或其他。我只推荐一个.json
:
exports.redirect = async (req, res, next) => {
res.json({ Error: 'Plase try again', url: '/signup' });
}
.then(res => res.json())
.then(result => {
div.insertAdjacentHTML('afterend', `<div id="response">${result.Error}</div>`);
setTimeout(() => window.location = result.url, 5000);
})
还要确保将回调传递给setTimeout
,并使用window.location
,而不是windows.location
。
你的最后一个.catch(err => {
块也是多余的,它永远不会被输入,无论如何也没有任何意义 - 随意完全删除它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句