【问题标题】:Getting duplicate results on Express API endpoint. How do I reset the search so that I get new results each time?在 Express API 端点上获得重复的结果。如何重置搜索以便每次都能获得新结果?
【发布时间】:2020-04-30 20:23:28
【问题描述】:

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

这里是实际端点的链接:(将“covid”一词更改为您喜欢的任何搜索词,如果您至少执行两次,即使您完成了新的搜索,也会显示上次搜索的数据搜索)

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

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

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

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
            });


  }
});


};

【问题讨论】:

    标签: node.js express endpoint


    【解决方案1】:

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

    【讨论】:

    • 天哪!太简单!非常感谢你的帮助!效果很好!
    • 我以前完全犯过这个错误,所以我很容易发现:)
    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多