Search code examples
javascriptexpressgetfetch

How can I send query parameters using fetch to server?


I have an express.js server that makes a HTTP GET Request to retrieve weather data. In my JavaScript, I obtain the latitude and longitude variables. I need to send those variables to my express.js server using fetch. How can I do this?

I have tried sending the query parameters as the body of the request object, but I learned GET requests cannot do that.

Express Server Code:

app.get("/data", (req, res) => {
url  =  `http://api.openweathermap.org/data/2.5/uvi?appid=${API}&lat=${latitude}&lon=${longitude}`;

axios
    .get(url)
    .then(response  => {
        res.send(response.data);
    })
    .catch(error  => {
        console.log(errorx);
    });
});

How would I get the latitude and longitude variables from my JavaScript?

I expect the express server to have the required variables and perform the GET request.


Solution

  • Query string parameters are part of the request URL.

    Try the following to pass latitude and longitude when you do a GET request assuming the endpoint is http://localhost:3000/data?lat=0&long=0

    app.get("/data", (req, res) => {
      // Add this to retrieve query string values
      let latitude = req.query.lat;
      let longitude = req.query.long;
    
      // Rest of your code
    });