I'm using the Twit Node module with Node.js to try to track certain hashtags for an app I'm writing and I'm not getting anything out of the Api other than an error saying "Error: Bad Twitter streaming request". As far as I can tell I've followed the documentation but I'm obviously missing something.
Here is the code, with a few bits redacted:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/', function(req, res) {
res.render('pages/index');
});
var http = require('http').createServer(app);
http.listen(80);
var io = require('socket.io').listen(http);
var twitterApi = require('twit');
var twitter = new twitterApi({
consumer_key: '***',
consumer_secret: '***',
app_only_auth: true
});
var stream = twitter.stream('statuses/filter', {track: '#twitter'});
stream.on('tweet', function(tweet){
console.log(tweet);
});
I'm working on an Ubuntu VM through Vagrant if that makes any difference?
Did you get the API credentials right ? 401 is usually returned with a unauthorized request, so I guess it must be with your API credentials.
You haven't provided access token and access token secret
Related
Im trying to send a POST from a client connected to this server to a external URL. I get a lot of 'CORS' errors. Im pretty sure that it's because i haven't allowed 'Access-Control-Allow-Origin' and etc on my Node.JS server. But i don't know how to do it. I have found another answers on the web, but none of them solved my problem.
Here is my server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const { instrument } = require('#socket.io/admin-ui')
var bodyParser = require('body-parser')
var clientesConectados = [];
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', function(req, res){
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
app.post('/', (request, res) => {
console.log("********************");
console.log(" >POST RECEBIDO!!");
console.log(res);
postData = request.body;
io.emit('message',postData);
console.log(postData);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Express has a middleware for CORS. Link here
Install npm package called cors
After installing, on your file add this line app.use(cors()) will solve your issue of cors error I hope.
Install cors package in your application
npm install cors
And then add these two lines in there
var cors = require("cors");
app.use(cors())
Else there are ways that set through header or you could use a proxy in your frontend but using cors package is simpler
For some reason I keep getting "http://127.0.0.1:3000/socket.io/socket.io.js" 404 not found when I look under chrome developer tools network. I have spent over an hour trying to understand why this isn't working because it was working fine before and I didn't think I changed anything.
Server:
var express = require('express'),
session = require('express-session');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var MongoStore = require('connect-mongo')(session);
var sessionMiddleware = session({
resave: false,
saveUninitialized: false,
secret: 'secret',
store: new MongoStore({url: "mongodb://localhost:27017/database"})
});
app.use(sessionMiddleware);
io.use(sessionMiddleware, function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
io.sockets.on('connection', function (socket) {
console.log("Socket connected");
});
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index');
});
app.listen(3000);
console.log('listening');
Pug File:
html
head
script(src="http://127.0.0.1:3000/socket.io/socket.io.js")
script(type='text/javascript', src='../javascripts/chat.js')
body
Client javascript:
try {
var socket = io.connect('http://127.0.0.1:3000');
} catch(e) {
console.log(e);
}
Change this:
app.listen(3000);
to:
server.listen(3000);
app.listen() creates a new and different server so the server that you have socket.io attached to is not the one that is actually listening and thus your socket.io server is not live and not able to handle the /socket.io/socket.io.js request or the incoming connection if the script file didn't first fail to load.
See this answer for more details on what app.listen() does and why it isn't what you want the way your code is laid out:
websockets, express.js and can’t establish a connection to the server
Note, you could use app.listen(), but you'd have to not create your own server and you'd have to capture the return value from app.listen() and use that as the server you pass to socket.io initialization:
var app = express();
var server = app.listen(3000);
var io = require('socket.io')(server);
Which is not quite how your code is structured (but you could rearrange things to do it this way).
Here's my app.js file.
var express = require('express'),
bodyParser = require('body-parser'),
oauthServer = require('oauth2-server'),
oauth_model = require('./app_modules/oauth_model')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }));
var jsonParser = bodyParser.json();
app.oauth = oauthServer({
model: oauth_model, // See below for specification
grants: ['password', 'refresh_token'],
debug: process.env.OAUTH_DEBUG,
accessTokenLifetime: 172800,
refreshTokenLifetime: 172800,
authCodeLifetime: 120,
});
// Oauth endpoint.
app.all('/oauth/token', app.oauth.grant());
// User registration endpoint.
app.post('/users', jsonParser, require('./routes/register.js'));
// Get user details.
app.get('/users', app.oauth.authorise(), require('./routes/users.js'));
app.post('/', app.oauth.authorise(), require('./routes/test.js'));
app.use(app.oauth.errorHandler());
app.listen(3000, function () {
console.log('Mixtra app listening on port 3000!')
})
When I send an invalid json body with POST request to localhost:3000/users the request goes to register.js and the validation code works there.
but strangely when I send valid JSON body, it says "Cannot POST /users" with a 404 Not Found HTTP status code and nothing in terminal log.
Note: I'm using postman to send the api requests.
It would be really great if someone could help me with this.
Thanks,
Joy
I don't see you using the jsonParser
You should use it before sending any json to it
app.use(jsonParser);
So I am new to express and io but I had a server running fine for webRTC but now there is a deprecated method in webRTC that only runs on https so I tried to create an https server but it starts and then immediately exits. I cannot figure out what is wrong and I do not get any errors. Also I am using an aws ec2 to run the express io server. Maybe someone can spot where in my syntax/implementation I am going wrong.
Note I have been googling around for the past half hour and cannot figure it out
Here is the code:
var connect = require('connect');
var https = require('https');
var fs = require('fs');
var express = require('express.io');
var app = express();
//app.http().io();
var PORT = 443;
var options = {
key: fs.readFileSync('../server.key'),
cert: fs.readFileSync('../server.crt')
};
app.https(options).io();
//var app = https.createServer(options, app1);
console.log('server started on port ' + PORT);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index.ejs');
});
app.listen(PORT);
app.io.route('ready', function(req) {
req.io.join(req.data.chat_room);
req.io.join(req.data.signal_room);
app.io.room(req.data).broadcast('announce', {
message: 'New client in the ' + req.data + ' room.'
})
})
Update
I am putting a bounty on this because I would like someone to provide me with a complete answer on setting up the server for production.
You need to add a rule for port 443 in a Security Group for your instance.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html might help.
I'm build an WP app using HTML5/js/CSS, and today i got a problem. I create a NodeJs server using socket.io fot chat. My server code:
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var mongodb = require('mongodb');
var url = 'mongodb://localhost:27017/chat';
var MongoClient = mongodb.MongoClient;
app.configure(function(){
app.set('port', process.env.PORT || 3456);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = require('socket.io').listen(server)
, guestNumber = 1
, nickNames = {}
, numuser = 0;
io.set('log level', 1);
io.on('connection', function (socket) {
...
});
In my app, i use: var socket = io.connect('myipserver:3456/');
IT NOT CONNECT to my server, but when i use browser to connect my ip server, it normal, and in my app, it got error: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
In package.appxmanifest, i checked Internet ( Client & Server ) Capabilities.
So, do i miss something in my app ? Plz help.
After some Googling I saw this question that has the same error code as your app. Seems to me that this error code says that the app does not see the server. So I don't think it's a socket-related error.
Try making a simple AJAX request to your server (with jQuery: $.get(myipserver:3456/some-static-file)). If it works, then it's something with the socket communications, otherwise the app does not see the server at all. Good point to start from, I guess.