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

API service return 200, but it is really a 404

本文关键字:实际上 服务 返回 API      更新时间:2023-09-26

我有这个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返回的响应中获取false,并抛出错误?

将"no response found"返回为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!') 
}

你可以使用承诺链将承诺从resolve转换为reject:

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像以前一样执行,但无效的数据已经被拒绝。