【问题标题】:A specific URL causes axios nuxt module to not run callback特定的 URL 导致 axios nuxt 模块不运行回调
【发布时间】:2019-12-22 05:10:33
【问题描述】:

所以我在我的 nuxt.js 页面上设置了两个名为“确认”和“删除”的按钮。单击每个按钮时,将分别运行confirm() 和delete()。这两个函数的代码几乎相同,唯一的区别是 URL 不同。运行 delete() 时,它使用 axios 执行 GET 请求,并且回调完美运行并执行我希望它执行的操作。但是,在运行 confirm() 时,它会执行请求但不会运行回调。

我认为 API 服务器可能没有响应。但是,当我检查日志时,实际上正在发送响应。

1zcu ——> GET /api/pending/delete/5d554a5d9ddb8079158eefcc 
1zcu <—— 200 OK 15 B application/json; charset=utf-8 (<—> 326.1 ms)
yefy ——> GET /api/pending/confirm/5d554a5c9ddb8079158eefcb 
yefy <—— 200 OK 14 B application/json; charset=utf-8 (<—> 540.9 ms)

所以我尝试更改 confirm() 函数中的 URL 以匹配 delete() 函数中的 URL,果然,它开始工作了。

功能

    confirm(id) {
      this.setConfirming(id);

      const url = CON_URL + id;
      this.$axios.$get(url).then((res) => {
        if (!res.error) {
          console.log(res)
          this.refresh();
        }
      });
    },
    discard(id) {
      this.setDeleting(id);

      const url = DEL_URL + id;
      this.$axios.$get(url).then((res) => {
        if (!res.error) {
          console.log(res)
          this.refresh();
        }
      });
    },

网址

const DEL_URL = "/api/pending/delete/";
const CON_URL = "/api/pending/confirm/";

按钮

<td v-if="!enquiry.isConfirming"><button v-on:click="confirm(enquiry._id)" class="button is-primary">Confirm</button></td>
<td v-if="!enquiry.isDeleting"><button v-on:click="discard(enquiry._id)" class="button is-danger">Discard</button></td>

表达端点

router.get('/delete/:id', (req, res) => {
    Pending.findOneAndDelete({ _id: req.params.id }, (err, pending) => {
        if (err) {
            res.json({ error: true });
        } else {
            res.json({ error: false });
        }
    });
});

router.get('/confirm/:id', (req, res) => {
    Pending.findOneAndDelete({ _id: req.params.id }, (err, pending) => {
        if (err) {
            res.json({ error: true });
        } else {
            const confirmed = new Booking(pending);
            confirmed.save((err, result) => {
                if (err) {
                    res.json({ error: true });
                } else {
                    res.json({ error: false });
                }
            });
        }
    });
});

【问题讨论】:

    标签: javascript express vue.js axios nuxt.js


    【解决方案1】:

    Promise.then 仅在任务无异常完成时执行。您可能还需要使用Promise.catch 附加错误条件的回调:

    this.$axios.$get(url)
        .then((res) => {
            console.info(res);
        })
        .catch((err) => {
            console.error(err);
        })
        .finally(() => {
            console.info('done');
        });
    

    【讨论】:

    • 我用不同的解决方案修复了它,但它导致我有一个新问题,你能帮我吗?我在这个问题中发布了答案。
    • 好吧,没关系,它仍然无法正常工作。它工作正常,因为我更改了 CON_URL 以匹配 DEL_URL。我会试试你的解决方案。
    • 我试过你的解决方案......它没有发现任何错误,也没有运行 .then() 回调。
    猜你喜欢
    • 2020-09-25
    • 2021-04-12
    • 2022-09-28
    • 1970-01-01
    • 2022-01-22
    • 2019-12-03
    • 1970-01-01
    • 2021-09-07
    • 2019-12-08
    相关资源
    最近更新 更多