【问题标题】:Axios doesn't give neither .then or .catch response after POSTAxios 在 POST 后既不给出 .then 也不给出 .catch 响应
【发布时间】:2021-09-16 17:00:08
【问题描述】:

我正在尝试使用 react/nodejs 在本地 SQL 数据库中发帖。幸运的是,它确实 POST 并且信息进入数据库。如果成功,我想在 .then() 中放置一个 alert(),如果出现错误,我想在 catch() 中放置另一个 alert()。问题是它在发布时会同时提供“成功”警报和“错误”警报,尽管它在数据库中发布的所有内容都很好。我错过了什么吗?

  const submitForm = () => {
    Axios.post('http://localhost:3001/api/insert',{
    manager:manager,
    decisionDate:decisionDate.toLocaleDateString(),

    }).then(alert('Success'))
    .catch(alert('Failure'))
  }

【问题讨论】:

  • 您立即调用警报两次,然后将 results 作为“回调”传递。
  • 如何修正你的错字:将alert('Success')更改为alert.bind(undefined, 'Success')

标签: javascript reactjs axios


【解决方案1】:

then 回调的语法不正确,这会导致错误被catch 捕获。将回调更新为以下内容:

  const submitForm = () => {
    Axios.post('http://localhost:3001/api/insert',{
    manager:manager,
    decisionDate:decisionDate.toLocaleDateString(),

    }).then(() => alert('Success'))
    .catch(() => alert('Failure'))
  }

【讨论】:

  • 我已经按照您所说的更改了代码,但 .then() 和 .catch() 都没有发出任何警报,但 POST 一直成功。我试过用 console.log() 代替 alert,但结果是一样的。
  • 您的环境可能不支持箭头语法() => {}。您可以使用函数语法代替.then(function () { alert('Success' })
【解决方案2】:

您的语法不正确,导致错误被catch 子句捕获。

将回调更新为以下内容:

axios.post('http://localhost:3001/api/insert', {
    manager:manager,
    decisionDate:decisionDate.toLocaleDateString(),
}).then(function (response) {
    console.log('Success', response);
}).catch(function (error) {
    console.log(error);
});

请参考axios documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2016-07-04
    • 2018-09-10
    • 2018-10-11
    • 1970-01-01
    相关资源
    最近更新 更多