Home>

I want to use express to output the results obtained using the Twitter API.

reference  

I was able to get the result of the query while looking at, but I couldn't successfully incorporate it into express.
How can I get the tweet acquisition result in json when accessing http: // localhost: 3000/twitter?

Can you borrow your wisdom? Please contact us if you have any necessary information.
Since it can be output to the console, the authentication system has determined that there is no problem.

twitter.js

var express = require ('express');
var router = express.Router ();
var Twitter = require ('twitter');
var client = new Twitter (omitted);
var data = client.get ('search/tweets', {q: 'Da Nang'}, function (error, tweets, response) {
    console.log (tweets);
 });
 router.get ('/', (req, res, next) =>{
    res.json (data);
 });
module.exports = router;

Because it is the first time to use api, it looks imitative, but thank you.

  • Answer # 1

    Referenceexpress.RouterPlease read the section carefully.

      

    Express routing

    Router is a function to create routing modules that can be used by calling them from other files.
    This alone does not work.

    module.exports = router;  

    All we are doing is registering the module created here so that it can be called from other files.
    To make it work, you need to call and start this module from another file.

    The question here is, are you trying to create something with enough lines to break the file into modules?
    If not, you don't need to use Router. Let's use app which is a standard function of express.
    If you do the following, it will work alone.

    const express = require ('express');
    const app = express ();
    const Twitter = require ('twitter');
    const client = new Twitter (omitted);
    const PORT = 3000;
    app.get ('/ twitter', async (req, res) =>{
        const data = await client.get ('search/tweets', (q: 'Da Nang'});
        console.log (data);
        res.json (data);
    });
    app.listen (PORT);
    console.log (`Server running at ${PORT}`);

    Here's another reason we moved the location of client.get ...
    The function given as an argument of app.get ishttp: // localhost: 3000/twitterCalled whenever there is a request to.
    On the other hand, the other process is called only once when the program starts.
    If there is client.get outside app.get,http: // localhost: 3000/twitterNo matter how many times you send a request to, the same response will always be returned unless you restart the program.
    What you're trying to create will surely be re-searching on every request, right?

    As mentioned above, it has become longer, but I hope you find it useful.