Certain URLs are known to prevent the callback function from executing in the axios nuxt module

I have implemented two buttons, "Confirm" and "Delete", on my nuxt.js page. Clicking each button triggers the confirm() and delete() functions respectively. Although the code for these functions is almost identical, the URLs they use are different. Interestingly, when delete() is executed, a GET request using axios is successful with the callback working as expected. However, when confirm() is called, the request goes through but the callback doesn't run.

Initially, I suspected that the API server might not be responding. Upon checking the logs, it was clear that the responses were being sent:

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)

To troubleshoot, I changed the URL in the confirm() function to match the one used in the delete() function, which resolved the issue.

Function Definitions

    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();
        }
      });
    },

URL Constants

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

Button Components

<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>

Express Endpoints

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 });
                }
            });
        }
    });
});

Answer №1

Promise.then is triggered only upon successful completion of the task. It's important to handle errors by attaching a callback using Promise.catch:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a method `Object.values()` available in TypeScript?

How can I iterate through all values of an Object in TypeScript that I want to use for filtering another array? I have searched on Google and came across Object.values(), but it seems like it doesn't work in TypeScript. Is there an equivalent method ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

Deploying Weinre on a Heroku server allows for remote debugging

I'm encountering some problems while trying to set up Weinre on Heroku. I successfully built the app by using a package.json with Weinre npm dependency and a Procfile that looks like this: web: node_modules/weinre/weinre --httpPort $PORT Initially, ...

Stopping a velocity.js animation once it has completed: is it possible?

For the pulsating effect I'm creating using velocity.js as a fallback for IE9, refer to box2 for CSS animation. If the mouse leaves the box before the animation is complete (wait until pulse expands and then move out), the pulsating element remains vi ...

The AJAX function triggers repeatedly upon each click

There is a form with two buttons: save & continue and save and exit. Each button has its own id, save_cont and save_exit respectively. When clicking the second button, the ajax action of the first button is triggered as well, preventing the URL redire ...

The swiper slider loop malfunctions when the number of slides is less than the double-value

When using **6 slides** with slidesPerView: 3, everything works fine. However, if I use 5 slides and set slidesPerView: 3, the loop stops after the last slide. var swiper = new Swiper('.swiper-container', { direction: 'ver ...

I am implementing a new method in the prototype string, but I am uncertain about its purpose

I am trying to wrap my head around the concept here. It seems like the phrase will pass a part of an array, in this case eve, to the phrase.palindrome method. This method will then process it. First, the var len takes the length of eve and subtracts 1 from ...

Steps for implementing a Toggle Navigation Bar in CSS

I'm looking to implement a show/hide navigation menu similar to the one showcased in this inspiration source: Code Snippet (HTML) <div id="menus"> <nav id="nav"> <ul> <li><a href="#">HOME</a></li> <li& ...

Rails encountered a syntax error while attempting to parse JSON data, due to an unexpected character found at line 2, column 1

I'm a beginner when it comes to using AJAX in Ruby on Rails. What I'm trying to achieve is that when a user clicks on a link with the class .link (redirecting to an external site, for example www.google.de), it should send data - specifically the ...

Calculate the total sum by adding the values of the radio buttons that have been selected and then display or

Seeking help to troubleshoot my code! I want to calculate the sum of selected radio button values and display it at the end. Can anyone assist me with this issue? Thanks in advance! <html> <head> </head> <script type="text/javas ...

Creating dynamic animations in React/Redux that respond to user actions

As I near the completion of my first React+Redux application, I am eager to incorporate animations throughout the different sections of the project. However, I have found that the existing solutions do not quite meet my expectations. The ReactCSSTransition ...

Error message: When the Submit Button is clicked for a post request, it results in a TypeError indicating that properties of undefined cannot be read (specifically 'name

Whenever I attempt to post the entry on MongoDB by clicking Submit, an error message pops up despite the fact that MongoDB is successfully connected to the server. Below is my router file const express = require('express'); const Club = require ...

Troubleshoot React component re-rendering issue

I'm currently facing a challenging bug that only occurs very sporadically (about once every few dozen attempts). During the render call, I'm determined to gather as much information as possible: I want to understand what triggered the rerender ...

Rotating Three.js around its own axis

I've been experimenting with creating a 3D spaceship that moves in a straight path. By adjusting the angles, you can make it roll and pitch up and down. Changing the Z angle causes the spaceship to roll correctly, while adjusting the X angle tips the ...

What could be causing audio playback issues in Expo-AV in React Native?

I'm in the process of developing an app that functions as a soundboard and plays various sounds when different buttons are pressed. To my surprise, instead of the audio playing, I encountered an error message that read: Possible Unhandled Promise Reje ...

Issue: Vue UI is unable to connect to Node.js Express CORS API using Docker-Compose

Edit: After checking the Log Output inside the Browser, I received the following message: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://127.0.0.1:8888' ...

Tips for sending two data elements from the frontend to the backend using an axios HTTP request

axios.delete(http://localhost:3001/api/delete/${movie}/${review}) The issue is that I am trying to pass 2 pieces of information, but it is not working. On the backend, my code looks like this: app.delete("/api/delete/:movie/:review", (req, res) => { co ...

Is there a way to implement a targeted hover effect in Vue Js?

I'd like to create a hover button that only affects the nested elements inside it. Right now, when I hover over one button, all the nested elements inside its sibling buttons get styled. Any ideas on how to fix this? <div id="app"> <butto ...

Utilizing JavaScript to Parse RSS XML Feeds Across Domains

Looking to parse an RSS (XML) file without relying on the Google RSS feed. I have attempted using JSONP, but it resulted in downloading the file and throwing an error "Uncaught SyntaxError: Unexpected token < ". $.ajax({ type: "GET", ur ...

Is there a way for me to manage the appearance of the printed document's layout?

I have successfully added 3 print buttons to my website, each one designed to print a specific portion (div) of the webpage. Here is the code snippet for this functionality: function printPage(id) { var html="<html>"; //html+="<link rel="st ...