iso53
iso53

Reputation: 72

How to add path variables to fetch api in Javascript?

Im using mockapi for a very simple project. In order to change data, i have to send PUT request. I can send the request using PostMan like in the pictures below. And everything works perfect. But i don't know where to add path variables in fetch api using Javascript. I know how to add body and i know how to add headers but i cannot figure out where to add path variables.

My code is:

async function getData() {
    let url = "https://blablabla/moves/:id";

    const fetchData = {
        method: "PUT",
        body: {
            roomid: 2512,
            move: "move 2",
            id: 2,
        },
        headers: new Headers({
            "Content-Type": "application/json; charset=UTF-8",
        }),
    };

    await fetch(url, fetchData)
        .then((response) => response.json())
        .then((data) => console.log(data));
}

And the Postman Screenshot: Postman Screenshot

I added the key: id part. All i want to know is that how can i add the "value: 2" part (that you can see in the picture) to fetch api. Any help will be appreciated.

I tried to fetch PUT request in javascript but couldn't figure out where to put Path Variables.

Upvotes: 0

Views: 1397

Answers (1)

Vinicius
Vinicius

Reputation: 324

There are no path variables in the fetch api, but you can pass the id in the string itself like so:

async function getData(id) {
    let url = `https://blablabla/moves/${id}`; // use string interpolation here

    const fetchData = {
        method: "PUT",
        body: {
            roomid: 2512,
            move: "move 2",
            id: 2,
        },
        headers: new Headers({
            "Content-Type": "application/json; charset=UTF-8",
        }),
    };

    await fetch(url, fetchData)
        .then((response) => response.json())
        .then((data) => console.log(data));
}

Upvotes: 0

Related Questions