繁体   English   中英

API服务返回200,但实际上是404

[英]API service return 200, but it is really a 404

我有这个VUEJS / VUEJS资源片段,该片段从API服务中获取数据。

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

并且它将始终返回200 OK响应...因此,如果它始终是“成功”,那么我真的不知道如何显示toastr.error

错误响应如下所示: {Response: "False", Error: "City not found!"}

我的问题

如何获取200 OK响应的Response中的false ,并引发错误?

返回“未找到响应”作为HTTP 200似乎是错误的API设计,但是如果您无法控制该API,则只需在成功函数中进行处理即可。

将错误处理代码放入函数中,并相应地调用它:

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

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

您可以使用诺言链将诺言从解决切换为拒绝:

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

重要的部分是:

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

因此,如果响应有效,并且数据包含Response: "False"则返回拒绝的诺言,否则,我们仅返回响应数据,然后将其包装在已解决的诺言中,此后下一个then像以前一样执行,但无效数据已被拒绝。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM