【问题标题】:Error 405 using axios post request in react native在本机反应中使用 axios 发布请求时出现错误 405
【发布时间】:2019-11-19 07:11:56
【问题描述】:

我在我的 expo react native 应用程序中使用 axios 发出发布请求,但我不知道为什么我的发布请求返回错误

请求失败,状态码 405

当我在邮递员上检查我的 API 时,它会向我显示预期的结果。我附加了在按钮上点击onPress 的方法。请检查并提供解决方案。

async onSubmit(ref) {
        if (ref.state.emailID && ref.state.password) {
            this.showLoader();
            await axios.post('http://apiurl.com/api/user/Userlogin?emailID=' + ref.state.emailID + '&password=' + ref.state.password,
                { emailID: ref.state.emailID, password: ref.state.password },
                { headers: { 'Content-Type': 'application/json' } })
                .then((response) => {
                    console.log('Innnn');
                    this.hideLoader();
                    console.log("response data: ", response.data);
                }).catch(err => {
                    this.hideLoader();
                    console.log("error: ", err.message);
                })
        }
    }

【问题讨论】:

  • 为什么要在请求 URL 中附加 emailId 和密码?你能否附上你在邮递员中所做的事情以及你得到什么回应的截图(在你的问题中)?

标签: react-native axios react-native-android expo


【解决方案1】:

好的,所以你的代码中有很多地方是错误的。

一开始就回答你的问题,我建议你添加withCredentials: true}

尝试在您的 axios 请求中添加 {withCredentials: true}

其次,使用 async 和 await,您不需要使用 .then 和 catch(而是使用 try..catch

async onSubmit(ref) {
    if (ref.state.emailID && ref.state.password) {
    try {
       this.showLoader();
         const networkReq = await axios.post('http://apiurl.com/api/user/Userlogin?emailID=' + ref.state.emailID + '&password=' + ref.state.password,
          {withCredentials: true},
         { emailID: ref.state.emailID, password: ref.state.password },
         { headers: { 'Content-Type': 'application/json' } })
       this.hideLoader();
       console.log(networkReq.data) 
    } catch (error) {
      this.hideLoader();
      console.log("error: ", err.message);
    }
 }
}

【讨论】:

  • 更新了答案
  • @ZaInKhAn 记录您的请求,我通常会创建payload,然后将其传递给axios.create。您的请求可能有问题。记录您正在传递的参数并确保没有未定义并且您正在传递正确的类型
  • 是的,我确定没有未定义的对象。
  • 根据您的建议更新我的代码后错误仍然存​​在
  • 非常感谢@iRohitBhatia。我犯了一个非常愚蠢的错误,我的 api 开发人员已将 api 请求从 post 更改为 get。现在一切正常,再次感谢您的帮助。
【解决方案2】:

我犯了一个非常愚蠢的错误,请求已从post 更改为get

【讨论】:

    猜你喜欢
    • 2019-09-05
    • 2020-03-06
    • 2020-04-24
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多