Home > OS >  How to get params passed in GET request?
How to get params passed in GET request?

Time:01-21

I am passing Wikipedia URL as params from client side link this:

const fetchData = () => {
    return fetch("http://localhost:5000/", {params: "https://en.wikipedia.org/"})
}

And trying to get it in server side link this:

app.get(`/`, (req, res) => {
    console.log(req.params);
});

But I am getting empty {}

How to get the Wikipedia URL?

CodePudding user response:

The issue you're facing is that you're trying to pass the params in the wrong place. When you call fetch("http://localhost:5000/", {params: "https://en.wikipedia.org/"}), you're actually passing an options object to the fetch function, which doesn't include a params property.

To pass the Wikipedia URL as a query parameter in the GET request, you need to append it to the URL:

const fetchData = () => {
    return fetch("http://localhost:5000/?url=https://en.wikipedia.org/")
}

Then on the server side, you can access the parameter using req.query.url:

app.get(`/`, (req, res) => {
    console.log(req.query.url);
});

Note that you can also use req.params to get the parameter but in this case, you're passing the url as a query parameter and not as a path parameter.

  • Related