简体   繁体   English

如何获取 api 响应错误和错误消息

[英]How to get api reponse error and error message

I'm new to using APIs so some help would be appreciated.我是使用 API 的新手,因此不胜感激。 I'm posting some data from a form using an API post request.我正在使用 API 发布请求从表单中发布一些数据。 I now need to display a message if this fails, depending on the error and status code.如果失败,我现在需要显示一条消息,具体取决于错误和状态代码。 I know I can get the status code like response.status but I also need to get the error itself and/or the error message.我知道我可以得到像response.status这样的状态码,但我还需要得到错误本身和/或错误消息。

So I'd need something like this所以我需要这样的东西

   $.ajax(settings).fail(function (response) {
     if(response.status === 404 && response.error === 'example_error'){
      alert('This failed.')
     }
   });

I also tried to get it something like this respsonse.json() but no luck.我也试图得到它这样的东西respsonse.json()但没有运气。 The network response in the console looks like this控制台中的网络响应如下所示

{"error":"example_error","message":"this is an error"}

My API call looks like this:我的 API 调用如下所示:

const formData = new FormData(thisForm).entries()

    var settings = {
      "url": "{{ section.settings.endpoint }}",
      "method": "POST",
      "timeout": 0,
      "headers": {
        "Content-Type": "application/json"
      },
      "data": JSON.stringify(Object.fromEntries(formData))
    };
    
    $.ajax(settings).done(function (response) {
      alert('success')

      form.reset()
    });

Any ideas how to do this?任何想法如何做到这一点?

Clearly it is not executing the alert block because the "status" property does not exists on the response object.显然它没有执行警报块,因为响应 object 中不存在“状态”属性。 You've got only "error" and "message".你只有“错误”和“消息”。 Your answer lies in your api's controllers, where you should take care of sending an appropiate http response, and not just a plain object, which it will carry some error message in case of a failure or a success message too.您的答案在于您的 api 控制器,您应该在其中发送适当的 http 响应,而不仅仅是简单的 object,它也会在失败或成功消息的情况下携带一些错误消息。

So, it all depends in which technology you are using in the backend and return an http response from your controllers, each technology would hand to you some methods to return those responses you need, which will carry a status code and other information.因此,这完全取决于您在后端使用哪种技术,并从您的控制器返回 http 响应,每种技术都会向您提供一些方法来返回您需要的那些响应,这些响应将携带状态码和其他信息。

For further learning you can look up for the anatomy of a http response and the official documentation of your backend tech about sending http responses.如需进一步学习,您可以查找 http 响应的解剖结构以及有关发送 http 响应的后端技术的官方文档。

I would suggest you simply console.log() the response and explore it, every object in js is a JSON object.我建议您只需 console.log() 响应并探索它,js 中的每个 object 都是 JSON object。

This looks quite old school, I suggest you use axios instead of ajax, in combination with promises.这看起来很老派,我建议你结合 Promise 使用 axios 而不是 ajax。 It's way easier:))这更容易:))


import axios from "axios";
import { config } from "../../configuration/config";

export function sendNotification(message: string): Promise<void> {
  return axios.post(
    `${config.http.servicesUrl}/notify/notifications`,
    {
      message,
    },
    {
      validateStatus: (status) =>
        (status >= 200 && status < 300) || status == 404,
    }
  );
}

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

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