【问题标题】:How to print the result from an axios post request如何从 axios 发布请求中打印结果
【发布时间】:2019-09-17 23:20:40
【问题描述】:

我想将来自服务器的令牌保存在 localStorage 中(服务器它是用 java 制作的),但下面的代码不起作用,所以我想打印 res 也看看我从服务器得到什么数据。

我尝试使用res.data.text() 和res.data.json() 打印到控制台,但不起作用。

    return dispatch =>{
        return api.user.login(userData).then(res =>{
             const token = res.data;
             console.log(token);
             //localStorage.setItem('jwtToken',token);

        })
}
import axios from 'axios'

export default {
    user:{
        login:(credentials) => axios.post('http://localhost:8080/api/auth/signin',credentials).then(res=>res.data.user)
    }
}

post 请求在服务器上工作,但是当我想打印时它卡住了。卡住是指当我按下登录按钮时没有任何反应。

如何打印到控制台res?

【问题讨论】:

  • 卡住是什么意思?你得到什么错误?另外,您的 api.user.login 是什么?你能把整个代码贴出来吗?
  • 你能不能创建一个沙盒
  • 实际打印的 res 是什么?
  • console.log(res) 将打印类似用户对象的内容,我猜是因为您已经从请求中返回了用户

标签: reactjs redux promise axios


【解决方案1】:
axios.post('http://localhost:8080/api/auth/signin',credentials)
    .then(
        res=>console.log(res.data.user)
    )

试试这个。我在.then 函数中写了一个console.log()。如果它仍然不起作用,请尝试记录 res 而不是 res.data.user 并检查结果

【讨论】:

    【解决方案2】:

    您可以尝试将 json 对象转换为字符串以在控制台上查看

    return dispatch =>{
            return api.user.login(userData).then(res =>{
                 const token = res.data;
                 console.log(JSON.Stringify(res));
                 //localStorage.setItem('jwtToken',token);
    
            })
    }
    

    【讨论】:

      【解决方案3】:

      对于成功的请求:

        return dispatch => api.user.login(userData)
            .then(res => console.log(res.data))
      

      对于不成功的请求:

      记录错误请求,您将打印错误对象。

          return dispatch => api.user.login(userData)
            .then(res => console.log(res.data))
            .catch(error => console.log(error.request)) 
      

      存储令牌:

      localStorage.setItem('jwtToken', JSON.stringfy(token))
      

      【讨论】:

        猜你喜欢
        • 2022-12-10
        • 2020-07-25
        • 2020-09-15
        • 1970-01-01
        • 2019-03-19
        • 2020-09-24
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        相关资源
        最近更新 更多