【问题标题】:AXIOS POST request is not sent and the function stops workingAXIOS POST 请求未发送,功能停止工作
【发布时间】:2022-01-15 11:04:33
【问题描述】:

我有一个登录功能,它应该触发 AXIOS POST 请求并获取响应并将其保存在 AsyncStorage 中(我在 React Native 中)。相同的代码适用于 React,但在这里我无法运行它。为了调试它,我放置了几个警报函数。登录功能并没有比“第二次调用”更进一步

我无法理解(现在好几天)为什么没有触发该功能的其余部分,如果是,则没有明显的错误。

这是我的功能:

export const login = (email, password) => async(dispatch) => {
    try {
        dispatch({ type: USER_LOGIN_REQUEST });

        alert('first call')
    
        const config = {
            headers: {
                "Content-type": "application/json"
            }
        }

        alert('second call')

        const { data } = await axios.post("url/login", {email, password}, config)
        alert('third call')


        dispatch({type: USER_LOGIN_SUCCESS, payload:data});
        alert('fourth call')

     
        alert(JSON.stringify(data) + `hello`)
        await AsyncStorage.setItem("userInfo", JSON.stringify(data))
        alert('final call')
        alert(userInfo)

        
    } catch (error) {
        dispatch({
            type: USER_LOGIN_FAIL,
            payload: 
                error.response && error.response.data.message
                    ? error.response.data.message 
                    : error.message,
        })

        alert("This login attempt is unsuccessful");
        alert(error)
        
    }
}

【问题讨论】:

  • 你为你的axios客户端配置了baseUrl吗?例如,尝试在 axios.post("url/login"... 中调用完整的 url(带有 http://)您还可以添加 try/catch 以查看有关错误的更多详细信息:try { const { data } = await axios.post("url/login", {email, password}, config) } catch(e) { console.log('Something went wront, see?', e) }

标签: reactjs react-native axios


【解决方案1】:

解决这个问题的方法(至少对我来说)原来是从 React Native 0.66 降级到 0.64。我总是收到 Expo 应用程序的警告,说 Expo SDK 最好使用 0.64。

当我没有其他追索权时,我降级到 0.64,没有更改代码,请求和 axios 帖子现在正在返回/执行。

如果有人遇到这种问题,请注意不会显示自己的版本错误,因为我已经卡了 4 天了。

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

如果你能确认 axios 请求确实发送了,那么你的 axios 请求(或者接收这个请求的服务器)一定有问题。

您是否检查了请求是否抛出错误并且您的catch 块被执行? (例如因为一些 CORS 问题)

如果catch 块未执行,则 axios 请求返回的承诺尚未解析/拒绝。造成这种情况的原因可能是服务器端问题 - 是什么让您的服务器无法响应?您是否使用正确的 URI 调用服务器?

在您的代码示例中,您指定路径url/login;这可以作为 Web 上的有效 URI(因为 axios 将此相对路径附加到您当前的 window.location.pathname),但是,移动应用程序没有网络应用程序拥有 domain 的概念。因此,相同的请求将在本机反应中失败。相反,请指定服务器的完整路径 ({protocol}://{domain}/{path}) 并查看是否可行。

【讨论】:

  • 谢谢 - 做了这一切,是的,我的端点实际上格式正确。我现在正在发送答案
猜你喜欢
  • 2021-06-08
  • 1970-01-01
  • 2018-01-08
  • 2020-06-05
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 2013-03-20
相关资源
最近更新 更多