2

I want to get a url with "username" paramater in it. How can i do it?

Example:

get url: api/find-username

paramater: username: "exampleusername"

Is it possible with node-fetch module?

Hasan Kayra
  • 101
  • 1
  • 6

1 Answers1

0

Yes, it is possible as node-fetch can construct just about any http GET request the server could want.

What you need to know from the target server is how the username parameter is supposed to be delivered. You can construct the request in node-fetch, but you have to construct it in the way that the target server is expecting (which you have not described).

For example, if the username is supposed to be in a query parameter and you're expecting JSON results, then you might do it like this:

const fetch = require('node-fetch');

// build the URL
const url = "http://someserver.com/api/find-username?username=exampleusername";
fetch(url)
  .then(res => res.json())
  .then(results => {
     console.log(results);
  })
  .catch(err => {
     console.log(err);
});

I will mention that constructing the proper URL is not something you guess on. The doc for your target server has to tell you what type of URL is expected and you must construct a URL that matches what it is expecting. It is typical to put parameters in a query string for a GET request as shown above, but when there is one required parameter, it can also be put in the URL path itself:

const fetch = require('node-fetch');

// build the URL
const url = "http://someserver.com/api/find-username/exampleusername";
fetch(url)
  .then(res => res.json())
  .then(results => {
     console.log(results);
  })
  .catch(err => {
     console.log(err);
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Can you show the server.js `app.get` function using `express`? I want to do a client-server api, so need the server. From [this SO](https://stackoverflow.com/questions/9577611/http-get-request-in-node-js-express) question I cannot see any `fetch` example. – Timo Dec 28 '21 at 14:49
  • 1
    @Timo - That doesn't really have anything to do with this question so it would be off-topic here. The express documentation has examples in it and there are thousands of articles on the web. If you get stuck after reading those, then I'd suggest you write your own question and show your existing code and describe where you got stuck. – jfriend00 Dec 28 '21 at 21:35