首页 > 解决方案 > 为什么请求没有被传递并根据请求刷新到 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);
     });
 };

标签: javascriptreactjsaxios

解决方案


根据我从您的帖子中了解到的情况,您希望在发送 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);
     });
 };

推荐阅读