我想得到一个带有"username“参数的url。我该怎么做呢?
示例:
获取url: api/find-username
参数:用户名:"exampleusername“
是否可以使用node-fetch模块?
发布于 2021-05-21 08:48:08
是的,这是可能的,因为node-fetch几乎可以构造服务器想要的任何http GET请求。
您需要从目标服务器了解的是如何传递username参数。您可以在node-fetch中构造请求,但必须以目标服务器期望的方式构造它(您还没有描述)。
例如,如果用户名应该在查询参数中,而您期望的是JSON结果,那么您可以这样做:
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);
});我要提到的是,构造正确的URL不是你所能猜测的。目标服务器的文档必须告诉您需要什么类型的URL,并且您必须构造一个与其期望的URL相匹配的URL。通常将参数放在GET请求的查询字符串中,但当有一个必需的参数时,也可以将其放在URL路径本身中:
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);
});https://stackoverflow.com/questions/67627747
复制相似问题