【问题标题】:500 error while doing a put/post/patch request in react native ios在本机 ios 中执行 put/post/patch 请求时出现 500 错误
【发布时间】:2020-04-01 03:14:33
【问题描述】:

我正在尝试为我的 react native (0.60.4) ios 项目创建一个 put 请求,每次我这样做时,我都会在提出请求时收到 500 错误。我在执行 post 或 patch 方法时也遇到了同样的错误。我在尝试使用邮递员发出请求时也收到 500 错误。

我的 sql 更新工作正常,因为我已经针对数据库运行了脚本并收到了预期值,这只是更新了一个布尔值。

这是我在 redux 中的更新方法

export const setChecklistItemToComplete = checklistItemId => {
  var checklistItemInstance = axios({
    method: 'put',
    url: `http://localhost:8080/xxxxxxxx/${checklistItemId}`,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'Access-Control-Allow-Origin': '*'
    }
  })
  console.log('checklistItemInstance: ', checklistItemInstance)
  return {
    type: MARK_CHECKLIST_ITEM_COMPLETE,
    payload: checklistItemInstance.data
  }
}

这是我的控制器

  try {
    const db = req.app.get('db')
    const { MarkChecklistItemComplete } = db.checklistItem.put
    const { params = {} } = req
    const { checklistItemId } = params

    console.log('checklistItemId: ', checklistItemId) <---GETS TO HERE
    if (joi.string().guid(checklistItemId)) {
      throw new Error('The id is not in the correct format')
    }

    var checklistItemInstance = await MarkChecklistItemComplete({
      checklistItemId
    })

    res.status(200)
    res.json(checklistItemInstance)
  } catch (error) {
    res.status(500)
    res.json(error)
  }
}

我假设这与这里的代码无关,但更多的是应用程序本身的配置。但是发布它不会有什么坏处。如果你还有什么想看的,我很乐意分享。

【问题讨论】:

  • 你没有在你的 axios put 中发送任何数据
  • 另外,首先,确保你的 api 与 postman 兼容,然后尝试集成到 react-native
  • 第一个 http 500 意味着您的后端无法响应您的请求。您在使用 put 时没有发送任何正文,但它不是前端问题。它必须在后端处理。在我看来,你必须检查后端抛出的字段......是必需的
  • @Neo 不需要一个主体,因为它只是在 SQL 本身中切换一个布尔值,但它仍然是一个更新。我确实检查了控制器中通过的 Id,如果该值超出了 guid/uuid 的格式(它不是),则会引发错误,因此它为什么会调用脚本,但这就是它失败。我在某处读到使用 React Native 和 ios 进行开发需要使用 https,这就是我提到应用程序配置的原因。

标签: ios node.js react-native express axios


【解决方案1】:

这就是你进行 10 小时的编码狂欢时发生的事情......

我在控制器中的 if 语句正在检查 checklistId 值,如果 id 格式正确,则会引发错误。我没有反转支票的价值...

if (joi.string().guid(checklistItemId)) {
      throw new Error('The id is not in the correct format')
    }

   if (!joi.string().guid(checklistItemId)) {
      throw new Error('The id is not in the correct format')
    }

【讨论】:

  • 当时您可能想将此答案标记为“正确”,或者只是将您的问题删除为社区不必要的问题:) 这有点令人困惑,因为react-native 在问题的标题中。
  • 不能删除它,也不能标记它直到明天:( @E.Dn
【解决方案2】:

react-native 请求没有任何问题,因为您在 try catch 代码块中遇到错误,因此请求本身没问题。正如你所说,你通过 Postman 得到了同样的错误。

据我所知,您使用 PUT 请求,但您没有使用任何正文。此外,您的代码没有到达 res.status(200) 行,但到达了这一行 console.log('checklistItemId: ', checklistItemId)。所以错误肯定是在调用MarkChecklistItemComplete({ checklistItemId }) 函数。所以要么checklistItemId 有一些错误/意外的值,要么函数MarkChecklistItemComplete 内部包含错误。

【讨论】:

  • 所以 MarkChecklistItemComplete 是 sql,正如我所说,我已经测试过运行它,并且将布尔值切换为 true 可以按预期工作。这是一个 put,因为它正在对数据库进行更新,但没有正文,因为不需要正文来将值切换为 true。
猜你喜欢
  • 1970-01-01
  • 2019-01-19
  • 2020-04-24
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多