我刚开始使用 nodeJS 和 npm 模块。
使用模块 twit
,我可以向 Twitter API 发出 GET 请求并搜索推文。
var Twit = require('twit')
var T = new Twit({ `login details`})
T.get('search/tweets', { q: 'banana since:2011-07-11', count: 100 }, function(err, data, response) {
console.log(data)
})
我正在尝试构建一个简单的用户浏览器页面,用户可以在其中输入自己的查询参数。我知道模块是服务器端的,我们不能在浏览器上使用它们。我也无法使用 browserify
因为 twitter 使用 Oauth 方法,这意味着您无法从浏览器访问它。
有没有办法将查询参数从浏览器传递回服务器代码,然后将该结果传递回浏览器?
T.get('search/tweets', { q: {user options}, function(err, data, response) {
console.log(data)
})
我们可以使用 socket.io
来传输 Twitter 数据,但如何将它用于 REST API?
最佳答案
Nodejs
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const Twit = require('twit');
...
const T = new Twit(LOGIN_DETAILS);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/search', function (req, res, next) {
T.get('search/tweets', {q: req.body.searchQuery, count: 100}, function (err, data, response) {
return res.json({
data: data
});
});
});
客户端
...
$.ajax({
url: "{API_URL}/search",
type: "POST",
dataType: 'json',
data: JSON.stringify({
searchQuery: SearchQuery
}),
contentType: "application/json; charset=utf-8",
success: function (msg) {
console.log(msg);
// do something with the response
}
});
$ 是 jQuery,了解更多关于 jquery ajax 的信息
关于javascript - 使用 Node JS 从浏览器的用户输入中检索 twitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56727680/