aba2s
aba2s

Reputation: 520

How can I pass a variable with url on javascript fetch() method?

I have to fetch data from my django api. In the url to fetch (http://127.0.0.1:8000/api/network/1/edges/) there are a number (pk integer) which can change. It can be http://127.0.0.1:8000/api/network/2/edges/ or http://127.0.0.1:8000/api/network/3/edges/. It depends on the current network. How can I handle this integer as variable ? I try this from (How to pass a variable with url on javascript fetch() method?) but it does not work

// Fetch data from api.
    var edges_from_api;
    var network_id = 1;
    fetch('http://127.0.0.1:8000/api/network/{network_id}/edges/')
        .then((response) => {
            return response.json()
        })
        .then((data) => edges_from_api=data)

Upvotes: 0

Views: 829

Answers (1)

sooraj
sooraj

Reputation: 344

use template literals

    var network_id = 1;
    fetch(`http://127.0.0.1:8000/api/network/${network_id}/edges/`)

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Upvotes: 4

Related Questions