我正在构建一个基于用户输入的网站,然后搜索Twitter的API。如果我硬编码搜索内容,我就可以使用它了:
app.js(node express)
var express = require('express')
var app = express()
var Twit = require('twit')
app.use(express.static(__dirname + '/public'));
var T = new Twit({
consumer_key: 'bla'
, consumer_secret: 'bla'
, access_token: '35929248-bla'
, access_token_secret: 'bla'
})
//get based on search term, count, location, etc
app.get('/tw', function (req, res) {
T.get('search/tweets', { q: 'beverly hills playhouse', count: 100}, function(err, data, response) {
res.send(data);
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
这是我的jquery:
$(function () {
$("#search-button").click(function() {
$.getJSON(
//URL of web service
"http://localhost:3000/tw"
).done(function (result) {
console.log(result);
});
});
});
现在,根据用户在HTML上的输入,我想改变的是q:' beverly hills playhouse'和count:我猜其他所有其他get方法的变量我将使用。
答案 0 :(得分:0)
如果您将请求作为发布请求发送到您的服务器,您可以在请求中发送从jQuery获得的信息,然后在服务器端使用您刚发送的请求信息将api调用发送到twitter。我建议调查的是:
body-parser - https://www.npmjs.com/package/body-parser(用于解析传入的请求并转换为易于使用的json对象)
ajax调用和承诺 - http://api.jquery.com/jquery.ajax/(用于使javascript执行辅助任务)
postman - https://www.getpostman.com/(一种很好的api请求方式)
与编程中的大多数事情一样,有很多方法可以做你想要的。我没有测试过这段代码,但我可能会这样做
app.js:
var express = require('express')
var app = express()
var Twit = require('twit')
//Include body-parser for middleware
var boadyParser = require( 'body-parser' )
//This sets bodyParser to act as middleware and go over all requests sent to your server
app.use( bodyParser.json() );
app.use(express.static(__dirname + '/public'));
var T = new Twit({
consumer_key: 'bla'
, consumer_secret: 'bla'
, access_token: '35929248-bla'
, access_token_secret: 'bla'
})
//get based on search term, count, location, etc
app.post('/tw', function (req, res) {
var search = req.body.search;
T.get('search/tweets', { q: search, count: 100}, function(err, data, response) {
res.send(data);
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
jQuery的:
$(function () {
<input type="text" id="search" placeholder="Enter twitter search terms">
$("#search-button").click(function() {
$.ajax({
url: "http://localhost:3000/tw",
method: "POST",
data: $("#search").val()
})
});