Home > database >  How to axios.get by object ID?
How to axios.get by object ID?

Time:10-16

I am trying to figure out how to used axios.get by the object ID using forms. My current JS code is pulling all the array of objects from the API.

This is the snip-it of the array of objects from the API.

enter image description here

The HTML form where the object id is to be entered is.

            <form name = "axiosget">
            <input type ="text" id ="id" placeholder="Get Id"/>
            <button>Submit</button>

        </form>

And this is my axios.get code with the api "https://api.sample.io/todo"

const axiosGet =document.axiosget;

axiosGet.addEventListener("submit", function(event){ event.preventDefault()

const axiosGetId = {
    id: axiosGet.id.value
}

axios.get("https://api.sample.io/todo", axiosGetId)
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

})

My POST works with suing this method. This is the HTML forms for the POST

   <form name = "newpost">
        <input name ="title" placeholder="Title"/>
        <input name ="description" placeholder="Description"/>
        <input name="imgUrl" placeholder="Image Url"/>
        <button>Submit</button>

    </form>

and this is the js code

const newPost =document.newpost;

newPost.addEventListener("submit", function(event){ event.preventDefault()

const newPostItem = {
    title: newPost.title.value,
    description: newPost.description.value,
    imgUrl: newPost.imgUrl.value,

 
};

axios.post("https://api.sample.io/todo", newPostItem)
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

});

CodePudding user response:

On a REST API you should simply GET your "number 1" post with a simple /todo/1 route, so you can do a

const axiosGetId = {
    id: axiosGet.id.value
}

axios.get(`https://api.sample.io/todo/${axiosGetId}`)
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

or concatene the id at the end of the route "https://api.sample.io/todo/" axiosGetId

or pass it as a get value to the server with "https://api.sample.io/todo?id=1"

the difference with your POST method is that you don't send the ID when you save your resource, because the server does it for you and decides which ID will be your new todo

CodePudding user response:

Check endpoint api, maybe you can add query parametr in request like this?

axios.get("https://api.sample.io/todo/123")
or
axios.get("https://api.sample.io/todo?id=123")
or
axios.get("https://api.sample.io/todo?_id=123")
  • Related