【问题标题】:API service return 200, but it is really a 404API 服务返回 200,但实际上是 404
【发布时间】:2016-10-11 17:53:38
【问题描述】:

我有这个从 API 服务获取数据的 VUEJS / VUEJS 资源 sn-p。

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 并抛出错误?

【问题讨论】:

  • 除非您的 api 服务器返回 404 作为响应,否则您无法在不使用某种 hack 的情况下执行此操作(即,如果您收到的响应不是您所期望的,请检查您的响应并从那里调用错误函数)。

标签: javascript vue.js vue-resource


【解决方案1】:

将“未找到响应”作为 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!') 
}

【讨论】:

  • 谢谢!出现错误ReferenceError: Can't find variable: onError,行}, onError);
【解决方案2】:

您可以使用 Promise 链来将 Promise 从 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像以前一样执行,但无效数据已被拒绝。

【讨论】:

    猜你喜欢
    • 2012-04-09
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 2013-04-08
    • 2018-06-28
    • 2017-10-26
    相关资源
    最近更新 更多