【发布时间】:2021-09-12 17:02:55
【问题描述】:
我正在做一个小项目,通过节点服务器向 Twitter API v2 发出 GET 请求来学习如何使用 API。
对于获取请求,我使用的是 Node 内置的 https 包。
我做了一个基本的 GET 请求,它返回一个用户最近 10 条推文的列表。 我认为为了增加我可以获得的推文数量,我必须创建一个单独的参数对象,然后在 get 请求中实现它。
现在我的函数如下所示:
function getTweets() {
const options = {
host: "api.twitter.com",
path: `/2/users/${userId}/tweets`,
headers: {
authorization:
`Bearer ${bearerToken}`,
},
};
https
.get(options, (response) => {
let data = "";
response.on("data", (chunk) => {
data += chunk;
});
response.on("end", () => {
let jsonObject = JSON.parse(data);
tweetObjects = jsonObject.data;
tweetObjects.map((item) => {
let tweetWords = "";
tweetWords += item.text;
userTweets.push(tweetWords);
});
const result = userTweets.flatMap((str) => str.split(" "));
console.log(result);
});
})
.on("error", (error) => {
console.log(error);
});
}
现在我的请求中只有 options 对象,其中包含主机、路径和标头。
这就是我想要做的:
function getTweets() {
const options = {
host: "api.twitter.com",
path: `/2/users/${userId}/tweets`,
headers: {
authorization:
`Bearer ${bearerToken}`,
},
};
let params = {
max_results: 100,
};
https
.get(params, options, (response) => {
let data = "";
response.on("data", (chunk) => {
data += chunk;
});
response.on("end", () => {
let jsonObject = JSON.parse(data);
tweetObjects = jsonObject.data;
tweetObjects.map((item) => {
let tweetWords = "";
tweetWords += item.text;
userTweets.push(tweetWords);
});
const result = userTweets.flatMap((str) => str.split(" "));
console.log(result);
});
})
.on("error", (error) => {
console.log(error);
});
}
但我明白了
throw new ERR_INVALID_ARG_TYPE('listener', 'Function', listener);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received an instance of Object
at checkListener (events.js:131:11)
at ClientRequest.once (events.js:496:3)
at new ClientRequest (_http_client.js:215:10)
at request (https.js:326:10)
at Object.get (https.js:330:15)
at IncomingMessage.emit (events.js:388:22)
at endReadableNT (internal/streams/readable.js:1336:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
code: 'ERR_INVALID_ARG_TYPE'
【问题讨论】:
-
这个节点是原生的 https.get 吗?第一个参数是 URL 或 OPTIONS(选项有 URL)...如果不是,那么它是什么
-
是的@JaromandaX 那是节点 https.get。我将 URL 放在选项对象中。
-
https.get 接受参数,如 (string, object, function) 或 (object, function) ...你用 (object, object, function) 调用它 - 查看问题
标签: javascript node.js twitter https