简体   繁体   中英

node-fetch GET with a parameter

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?

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM