0

I'm using Express to create an endpoint so that I can access it with API calls. When I do the search the first time, everything works great, but if I do it again, I get the results from the previous time PLUS the results from the new search. How do I get the search results to reset each time?

Here is a link to the actual endpoint: (change out the word "covid" for any search term you like and if you do it atleast twice, you will see data from your last search displayed even after you have done a new search)

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

Thanks so much for any help you can offer!

This is the app.js file which calls the twitterRouter and with app.use creates the endpoint at /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;

I was under the impression that using res.send() ends the API search, but it doesn't seem to end.

Then here is the actual API call and where it generates the data for the endpoint:

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


  }
});


};
Nova
  • 69
  • 1
  • 8

1 Answers1

2

Your locationsToSend variable is in global scope which is persisted as long as your express app is running. You should initialize that variable inside the search/tweets callback and you'll get the behavior you want. That way each request will get its own locationsToSend to work with rather than the global one.

Brad Fellows
  • 171
  • 8