javascript - 为什么请求没有被传递并根据请求刷新到 axios
问题描述
将电子邮件和密码作为 post 请求发送到 axios 服务器以标头中的不记名令牌进行响应。我们通过将令牌存储在本地存储中来实现登录功能。但是,有时您会运行代码,有时则不会。不运行时,点击按钮刷新页面,同时打开Chrome开发者工具的控制台窗口。通过控制台日志检查的结果,该函数被执行,但似乎在向 axios 发出请求时发生了刷新。我可以看看有什么问题吗?
https://codesandbox.io/s/craky-sun-l36oz
const login = () => {
setLoading(true);
axios({
url: 'api url',
method: 'POST',
data: {
email: email,
password: password,
},
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
token = response.headers.authorization;
console.log(token);
localStorage.setItem('authorization', token);
alert('success');
setLoading(false);
})
.catch((error) => {
console.log(error.status);
});
};
解决方案
根据我从您的帖子中了解到的情况,您希望在发送 Axios 请求时阻止页面刷新。(幸运的是,因为我来自韩国,所以我能更懂你用谷歌翻译的英语。)
您可以event.preventDefault()
在登录处理程序中使用来阻止页面刷新。我在您的代码沙箱中测试了下面的代码,页面不再刷新。
const login = (e) => {
e.preventDefault()
setLoading(true);
axios({
url: 'api url',
method: 'POST',
data: {
email: email,
password: password,
},
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
token = response.headers.authorization;
console.log(token);
localStorage.setItem('authorization', token);
alert('success');
setLoading(false);
})
.catch((error) => {
console.log(error.status);
});
};
推荐阅读
- python - 如何使用openCV检测卫星航拍图像中的街道线?
- python - 无法使用 CBV 在 Django 中更新 InlineFormset
- javascript - 此轮播中使用的动画名称是什么
- mysql - 使用此增量 ID 插入 MySQL
- excel - 隐藏 Excel 表格中的所有列,除了少数选定的列
- javascript - Recaptcha 正在移动设备上工作,但不在桌面上
- java - 使用 Apache Batik 对 SVG 文件进行正确缩进(漂亮的打印)
- c# - 未找到“EntityQueryable < ReportCompetency >”。确保实体类型已添加到模型中
- vba - 表格的vba选择范围
- sql - 重构 Oracle SQL 查询