提问者:小点点

使用节点Js和ejs构建Twitter API


我正在尝试使用节点js和EJS制作一个Twitter搜索API。我可以在我的node.js命令提示符上实现结果,但是,我不知道如何将命令提示符的输出传输到EJS中。我一直在想要在我的ejs文件中写些什么。请帮帮忙。

    ***//This is my index.js codes:***
    
    var express    = require('express');
    var bodyParser = require('body-parser');
    var twitterApi = require('./twitter');
    var app        = express();
    
    app.use(bodyParser.urlencoded({extended: false}));
    
    // Set EJS as templating engine
    app.set('view engine', 'ejs');
    
    
    app.get('/', function(req, res){
        res.render('home'); 
    });
    
    app.post('/get_tweets', function(req, res){
        var tweetName = req.body.handle;
        var tweets = twitterApi(res, tweetName);
        
    });
    
    app.listen(3000, () => console.log('listening at 3000'));




***//This is my twitter.js codes:***

var Twit = require('twit');

module.exports = function(res, tweetName) {
    var T = new Twit({
        consumer_key:         'xxxxx',
        consumer_secret:      'xxxxxx',
        access_token:         'xxxxxx',
        access_token_secret:  'xxxxxxx',
      });
    
      var params = {q: tweetName, count: 2};
      var tweets_to_display = [];
    
      T.get('search/tweets', params, function(error, search_results, response){
          if (!error){
          }
          var search = search_results.statuses;
          
          search.forEach(function(data){
              var dataObject = {
                ID: data.id,
                ID_STR: data.id_str,
                Tweet: data.text
              };
              tweets_to_display.push(dataObject);
          });
          res.render('home', {tweets: tweets_to_display});
      });
}

共1个答案

匿名用户

//最后,我的ejs代码:正如你们看到的,我在这部分被困住了。我已经尝试使用ejs语法为每个循环做了,但是没有回复。可能是我输入的值错了。

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>Home Page</title> 
      
    <style type="text/css" media="screen"> 
        body { 
            background-color: skyblue; 
            text-decoration-color: white; 
            font-size:2em;  
        } 
    </style> 
</head> 
  
<body> 
    <center>This is our home page.</center> 
    <div class="container">
        <div class="form mb-2 mt-2"> 
            <form action="get_tweets" method="POST">
                <h1>Twitter Search</h1>
                <div class="input-group">
                <input type="text" name="handle" placeholder="Search" required type="text">
                <input type="submit" value="Search">
                </div>

            </form>
        </div>
    </div>

      
    
</body> 
  
</html>