简体   繁体   中英

AngularJS: How to detect if there is not a response in $http

I have this code in AngularJS:

$http({
  url: my_url,
  method: "GET",
  data: null,
  headers: {
    "Content-Type": "application/json",
    "my-token": "mytoken",

  }
}).then(function(response, err) {
  console.log(response)
  console.log(err)
});

When the URL is correct and the status is 200 , the response is displayed with status 200 . But I want now to test with a wrong Url, then nothing is displayed, neither response nor error, so how to detect if there is no response?

By reading the $http documentation you can handle errors inside your error callback function. Also take a look at this HTTP Status Code list . Any 4xx status code eg 404 - not found will end inside the errorCallback function. You are also be able to handle the HTTP status by accessing response.status inside your callback functions.

Please note that there is always a response / HTTP Status code while performing an HTTP-Request.

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

>> Demo fiddle

then takes two functions as parameters. First is called for success and Second is called for error . This is called promise .

Use following code to catch error:

.then(function(response) {
    // Success
}, function(error) {
    // Error
})
$http({
    url: my_url,
    method: "GET",
    headers: {
        "Content-Type": "application/json",
        "my-token": "mytoken",

    }
}).then(function(response) {
    console.log(response)
}, function(error) {
    console.log(error);
    console.log(error.data);
});

Add a function as second parameter to .then() will track error cases for http calls.

问题在于此行,应将其删除“ my-token”:“ mytoken”,谢谢!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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