在Express API终结点上获取重复结果.如何重置搜索以便每次都能得到新结果



我正在使用Express创建一个端点,以便可以通过API调用访问它。当我第一次搜索时,一切都很好,但如果我再次搜索,我会得到上一次的结果加上新搜索的结果。如何每次重置搜索结果?

这里有一个指向实际端点的链接:(为你喜欢的任何搜索词去掉"新冠肺炎"一词,如果你至少做两次,即使你做了新的搜索,你也会看到你上次搜索的数据(

https://laffy.herokuapp.com/search/covid

非常感谢你能提供的任何帮助!

这是调用twitterRouter的app.js文件,并使用app.use在/search/:searchTerm:处创建端点

app.js

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const indexRouter = require('./routes/index');
const twitterRouter = require('./routes/twitterCall.js');
const top20 = require('./routes/twitterTop20.js');
const app = express();
app.set('views', path.join(__dirname, 'views'));
// app.set('port', process.env.PORT || 3001);
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
//creates route to use search at /search/
app.use('/search/:searchTerm', twitterRouter.search);
//creates route to access to get the top 20 Twitter hashtags trending
app.use('/top20', top20); 
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;

我的印象是使用res.send((结束了API搜索,但它似乎并没有结束。

然后是实际的API调用,它在这里为端点生成数据:

twitterCall.js

//twitter file that searchs for tweets specified in params.q
var Twitter = require('twitter');
var config = require('../config/config.js');
var express = require('express');
var router = express.Router();

var T = new Twitter(config);
var locationsToSend = [];
exports.search = (req, res) => {
if (req.body == null) {
res.status(404).send( {
message: "Search can not be blank"
})
}
var params = {
q: req.params.searchTerm,
count: 1000,
result_type: 'recent',
lang: 'en'
}

//Initiate your search using the above parameters
T.get('search/tweets', params, function(err, data, response) {
//if there is no error, proceed
if(!err){
// Loop through the returned tweets
for(let i = 0; i < data.statuses.length; i++){

if (data.statuses[i].user.location!==null && data.statuses[i].user.location!=="") {
locationsToSend.push({
id: data.statuses[i].id_str, 
createdAt: data.statuses[i].created_at,
text: data.statuses[i].text,
name: data.statuses[i].user.screen_name,
location: data.statuses[i].user.location
});
}
}
res.send(locationsToSend);
} else {
console.log(err);
return res.status(404).send({
message: "error searching " + err
});

}
});

};

您的locationsToSend变量在全局范围内,只要您的express应用程序正在运行,它就会一直存在。您应该在search/tweets回调中初始化该变量,这样您就会得到所需的行为。这样,每个请求都将获得自己的locationsToSend,而不是全局请求。

相关内容

最新更新