javascript - Response.redirect() 不是 vanilla JS 中的函数?
问题描述
在收到来自 post fetch 的响应后,我试图重定向到另一个页面,但正如标题所说,它不起作用。
这些是功能:
// send/post json
async function postData(json_data, api_path) {
const response = await fetch(api_path, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: json_data,
redirect: 'follow'
});
console.log("postData response: ", response);
return response;
}
// send JSON data to server on /api/${destination}
function saveSettings(form, destination) {
let json_data = toJSONstring(form);
let res;
console.log(json_data);
postData(json_data, `/api/${destination}`)
.then((response) => {
res = response;
if (!response.ok) {
throw new Error(`HTTP error, status = ${response.status}`);
}
return response.text();
}).then(text => {
if (destination === 'network/post') {
connected = false;
updatingToast(`You are no longer connected to the device !`, false);
updatingToast(`Please navigate to ${text}`, true, text);
}
console.log('res: ', res);
res.redirect(res.status, res.url);
});
}
每一次console.log();
回报Response {type: 'basic', url: 'http://192.168.0.100/dashboard', redirected: true, status: 200, ok: true, …}
如果我放在第一位response.redirect(response.status, response.url);
,then()
我会得到同样的错误。
那么,Vanilla JS 中是否存在response.redirect ?
我不想使用window.location.href
或任何其他类似选项,因为它绕过了 HTTP 身份验证标头。
解决方案
我看到你在 fetch 中给出了 'follow' 参数。
您可以使用下面的代码检查响应是否被重定向。如果它没有被重定向,您可以简单地更改窗口位置并强制重定向。
if (res.redirected) {
window.location.href = res.url;
}
编辑:
在对重定向方法进行了更多研究之后,我发现您需要切换 URL 和状态变量,请参阅:https ://developer.mozilla.org/en-US/docs/Web/API/Response/redirect
推荐阅读
- python - 一个基于“有效”数字运行的 if elif 程序
- java - 如何在 AWS ListObjectsV2Request 对象上设置下一个继续令牌
- python - 在python中使用字母和数字对列表进行排序
- php - 如何使用php将对象数组存储到redis缓存中
- android - Android意图过滤器有时不起作用
- python - 如何格式化字典列表中的字典对象?
- python - Pytorch required_grad=False 在 GPU 上运行时不冻结网络参数
- javascript - 从多个收音机和文本框中反应js更新值
- c# - 我正在尝试使用mailjet通过电子邮件发送消息,但是为什么其中无法识别单词版本
- python - 如何在 Python 中创建多机器人锦标赛风格的剪刀石头布游戏