The API response appears to be a successful 200 status code, however the actual result is a

I'm currently working with a VUEJS / VUEJS Resources code snippet that retrieves data from an API service.

fetchData: function(name){
          var self = this;
          self.$http.get('http://www.apiservice.com/', {
            params: {
               city: name
            },
            }).then((response) => {
            // success callback
            toastr.success('Success!');
            console.debug(response);
          }, (response) => {
             // error
            toastr.error('Something went wrong!')
          });
        }

However, the API always returns a 200 OK response, making it hard to determine when to display an error using toastr.error.

In case of a false response, it will look like this:

{Response: "False", Error: "City not found!"}
.

Here's my question

Is there a way to identify the false value in the response of a 200 OK return and trigger an error message?

Answer №1

When faced with an API that returns a "no response found" message with an HTTP 200 status code, it may signal poor API design. However, if you lack control over the API, your best option is to handle this in the success function.

To manage errors effectively, consider placing your error handling code within a separate function and invoking it appropriately:

fetchData: function(name){
    var self = this;
    self.$http.get('http://www.apiservice.com/', {
    params: {
       city: name
    },
    }).then((response) => {
        // Handling success
        if (response.Response === "False") {
            onError(response)
        } else {
            toastr.success('Success!');
            console.debug(response);
        }
    }, onError);
}

function onError(response) {
   toastr.error('Something went wrong!') 
}

Answer №2

If you want to toggle a promise from resolve to reject, you can utilize promise chaining:

fetchData: function(name){
          var self = this;
          self.$http.get('http://www.apiservice.com/', {
            params: {
              city: name
            },
            }).then(response)=>{
              if(response.Response === "False"){
                return Promise.reject(response)
              }else{
                return response
              }
            },(a)=>a).then((response) => {
              // success callback
              toastr.success('Success!');
              console.debug(response);
            }, (response) => {
              // error
              toastr.error('Something went wrong!')
            });
        }

The crucial part lies here:

then(response)=>{
  if(response.Response === "False"){
    return Promise.reject(response)
  }else{
    return response
  }
},(a)=>a)

So, if the response is legitimate and the data includes Response: "False", a rejected promise is returned. Otherwise, the response data is simply returned, wrapped in a resolved promise. Consequently, the subsequent then statement proceeds as normal, but any invalid data has already been rejected.

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

Customizing Echart tooltip appearance

I've integrated echart () into my Vue.js application, and I'm attempting to personalize the tooltip on a ring chart. However, I'm facing challenges in achieving this customization. My goal is to show my own JSON data in the tooltip when hove ...

Implementing a Variety of Textures and Images in a Three.js Scene

I am utilizing THREE.js to showcase a 3D spinning globe in the web browser. Along with that, I intend for an image to display around the rotating globe. Despite attempting to use the provided function, var img = new THREE.ImageLoader(); img.load("texture/ ...

The issue arises when the export function is triggered within the getStaticPaths() method, preventing the top-level

For my Next.js SSG (static site generation) app, I decided to optimize the database connection process by exporting a global promise from one file and then utilizing it in another file called controllers.js. This file houses multiple functions that directl ...

Error message: React router issue (Prop type failure: Prop `children` supplied to `Switch` is invalid, expecting a ReactNode.)

Trying to modify a component in order to create a login page, I attempted to modify App.js but encountered an error. warning.js?6327:36 Warning: Failed prop type: Invalid prop children supplied to Switch, expected a ReactNode. This is the code I have ...

Maximizing JavaScript efficiency: Returning a value within an if statement in an AJAX call

In my function, I have a condition that checks the idType. If it is 1, an ajax call is made to a php file to retrieve the name associated with the specific idName and return it. Otherwise, another example value is returned. function obtainName(idName, idTy ...

clear JavaScript array of elements

I've been grappling with this issue for hours now, and it seemed so straightforward at first; My goal with JavaScript is to iterate through an array, retrieve the current index value, and then remove that value from the array. I've read that spl ...

Transform shapefiles to geojson format using OpenLayers 5

As I embark on a new project that involves combining Vue.js and OpenLayers, I am thoroughly enjoying the process. While I have successfully implemented various functionalities like drawing, reading, and modifying vectors, I find myself stuck when it comes ...

Sending data with the request body using Express and Passport

I've created a login application using Express and Passport, but I'm having trouble directing the user to their specific user profile page. The goal is for users to fill out an HTML form and then be redirected to their own profile page (which dif ...

Using JavaScript in Internet Explorer 11, you can open multiple tabs without the UrlReferrer being null

I have tried numerous solutions to open multiple tabs in IE 11, but none of them seem to work for me. In Chrome, everything works smoothly with a simple window.open(url) command. When I try to open tabs using an iterative JavaScript code snippet, only one ...

The canvas is responsive to keyboard commands, however, the image remains stationary and unaffected

As I delved into the basics, incorporating canvas, CSS, and JavaScript, a question arose: should the image be housed in the HTML or the JavaScript code? Following this, I added a background color to the canvas and defined properties of the canvas in JavaSc ...

ng-select will solely output the term 'collection'

i am having an issue with a ng-select in my contact form. everything is being received correctly except for the value of the ng-select. Instead of getting the selected option from the ng-select, the system just returns the word "array". Below is the port ...

Extract the "_id" value from the array in the v-for loop and then store and reuse it in the data object // using vue-cli

Currently, I am iterating through [postArray] to retrieve various posts, each of which has its own unique "_id". My goal is to utilize this "_id" to add likes to the corresponding post. This is the v-for loop I am using: <div class="posts" v- ...

Redux repeatedly triggers re-rendering despite the absence of any changes in the state

This is my first venture into React-Redux projects. I was under the impression that React only re-renders when a component's state changes. However, I am currently facing confusion. The component is being re-rendered every 1 to 3 seconds even thoug ...

Send form information using the REST method

Can someone provide guidance on how to properly handle this endpoint in my code? @PostMapping("/createUser") public ResponseEntity<User> createUser(@RequestBody User user) {...} I am looking to implement a user creation feature on my HTML ...

What is preventing me from utilizing global variables in distinct HTML and JavaScript files?

I am facing a perplexing issue with my HTML files, specifically index.html and lobby.html. Within main.js, which is loaded in index.html, I attempt to load lobby.html using window.location.href. Despite trying various methods to define global variables i ...

Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated. https://i.sstatic.net/vBtXc.png When there are more than 9 items, the current layout ...

Describe a main method

I have 2 different components: Popup Box component This specific component is designed to only show the provided content in a popup box. Within this popup box, there are two methods called submit and cancel. DataForm Component The DataForm Component ...

Troubleshooting a Problem with the Horizontal Scrollbar in Dynamic jqGrid

Currently, I am working on an ASP.net MVC project where I have implemented both dynamic and static jq grids. However, I am encountering an issue with the horizontal scroll bar in my application. To address this problem, I attempted to modify the overflow ...

Is it possible to have the Target='_blank' attribute open the link in a new window instead of a new tab?

Is there a way to achieve this? When using Firefox, the link opens in a new tab, which I prefer to avoid users having to adjust settings in their browsers. I am looking for a solution where a pop-up contact form appears whenever a user clicks on 'co ...

Encountering an "Unexpected token '{'" error while attempting to import chart.js is likely due to the import call expecting only one argument

I'm currently working on a node.js app that utilizes chart.js for visualizations. However, I'm running into errors when trying to import and use Chart. To serve chart.js to the client, I used npm to install it and then added the following code: ...