0

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.

1
  • "https://blablabla/moves/2" This should work Commented Dec 15, 2022 at 18:36

1 Answer 1

0

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Even tough it upsets me that there isn't any way to add path variables in js, you seem to have answered my question. So i will mark this answer as the correct answer.
It's a pity that there is no way to pass path variables in fetch api... String concatenation to create an URL is the right way to add errors/vulnerabilities to the code. Imagine if id comes from a user input and is not URL-escaped.. What if id could contain a /? It's worth to at least encodeURIComponent the variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.