vue.jsgetelementbyidhttp-status-codesavailability

How to check http status code in vuejs and return value


I need to check the status code in vuejs, whether is it 200 or else. Here is my code, but i have errors.

methods:{
  userSearch(){
    let searchUrl = dataUrl+this.usersearch;
            
                fetch(searchUrl).then(statusCode => {
                    if(statusCode == 200){
                        message = "Not Available"
                        $("#availability").innerHTML = message
                    }
                    else {
                        message = "Available"
                        $("#availability").innerHTML = message
            }})

this should return in my p element with id="availability" whether the user is available or not, depending on the status code. I am calling this method in the input field on enter.


Solution

  • As @deceze pointed out, the fetch function resolves to a Response Object.

    You can see here how to properly handle the HTTP status of the response.

    But, for your code, it should be something like this:

    userSearch() {
        let searchUrl = dataUrl+this.usersearch;          
        fetch(searchUrl).then(response => {
            if(response.status == 200){
                message = "Not Available"
                $("#availability").innerHTML = message
            }
            else {
                message = "Available"
                $("#availability").innerHTML = message
            }
        })
    }
    

    As just part of the code was provided, there might be other causes for the error, that I cannot see with just this snippet.