Search code examples
javascriptvue.jsflaskrestful-url

How to insert a params in Fetch GET request?


I created a simple Flask's jsonify that I do not sure if I can call it as API, but I receive a JSON Object.

@app.route('/searchData/<int:id>',methods=["GET"])
def searchData(id):
    return jsonify(searchData(id))

Now using Fetch function, I cant pass the arg <int:id>, I don't if I can add params to Header in Flask to accepted the argument.

  async fetch(id){      
    const res = await fetch(
      "http://localhost:5000/searchData/",
        {
          method:"GET"
        }
    );
    const data = await res.json()
    console.log(data)
  }

Solution

  • Change " to back ticks to make it a string literal and add it with interpolation.

    async fetch(id){      
        const res = await fetch(
          `http://localhost:5000/searchData/${id}`,
            {
              method:"GET"
            }
        );
        const data = await res.json()
        console.log(data)
      }
    

    Using this style of interpolation makes it so much easier to read when you have a few params