如何在带有node.js的express.js上使用Twitter api显示推文?

时间:2018-07-18 01:31:58

标签: node.js express twitter

我正在尝试在客户端显示推特。已经尝试使用express-generator,但是它不起作用。 我可以在控制台中看到它们,但是无法将它们放到那里并在前面显示它们。我敢肯定它应该很简单。 请帮忙! 谢谢

server.js

const http = require('http')
const port = 5004;
const app = require('./app')
const mongoConnection = require('./db/config/mongoConnection')

http
   .createServer()
   .on('request', app)
   .on('error', function(error){
    switch (error.code){
     case 'EADDRINUSE':
      console.log('error')
     break;
     case 'EACCES':
     console.log('error de permisos')
     break;
     default:
     throw error;
    }
 })
.listen(port)

app.js

const express = require('express');
const twitsModel = require('./db/models/twits')
const controller = require('./controller')
const bodyParser = require('body-parser')
const twitter = require('twitter'); 
const config = require('./config') 
const client = new twitter(config); 

const params = {
     q: 'apple', count: 3 
}

const app = express()
.use(bodyParser.urlencoded({extended: true}))
.use(bodyParser.json())


client.get('search/tweets', params, function(error, tweets, response){
    console.log(tweets)
})
.use(express.static('./public')) // -----> it does not work


module.exports = app

1 个答案:

答案 0 :(得分:0)

主文件通常称为server.js app.js。两者都没有多大意义。在您的情况下,将代码保存在一个文件中更为简单。

const twitsModel = require('./db/models/twits')
const controller = require('./controller')
const bodyParser = require('body-parser')
const twitter = require('twitter'); 
const config = require('./config') 
const client = new twitter(config); 
const http = require('http')
const port = 5004;
const mongoConnection = require('./db/config/mongoConnection')

function sendTweet(req, res) {
  const params = {
     q: 'apple', count: 3 
  } 

 client.get('search/tweets', params, function(error, tweets, response){
    if(error) {
       console.log("Error getting tweets");
       return;
    }
    console.log(tweets);
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify(tweets)); // This line sends the tweets to the client making the http request.
    });
});


http.createServer(sendTweet).listen(port)