Making a GET request to my own authenticating user users/{id}/tweets in nodeJS and using V2 Twitter api, returns only tweets posted by my own authenticating user id.
What I need?
To GET all tweets both posted by myself and the ones that are showing in my timeline from users I follow.
Basically, the same result as in Twitter V1 GET statuses/home_timeline
How can I get this in V2?
index.js
const express = require("express");
const app = express();
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(express.json()); // for parsing application/json
const Twit = require("twitter-lite");
const config = require("./config");
const client = new Twit(config.appConfig);
function getTimeLineTweetsInV2() {
return new Promise(async (resolve, reject) => {
try {
let result = await client.get("users/tweets/1497521946694717448");
resolve(result);
} catch (error) {
console.log("errorrrrrrrrrr is", error);
reject(error);
}
});
}
(async function BotMain() {
let tweetsReceived = await getTimeLineTweetsInV2();
console.log(tweetsReceived);
})();
app.listen(3000, () => {
console.log("listeing on port 3000");
});
config.js
const dotenv = require("dotenv");
const path = require("path");
const ENV_FILE = path.join(__dirname, ".env");
dotenv.config({ path: ENV_FILE });
const appConfig = {
//define subdomain of twitter api URL e.g. api.twitter.com, streams.twitter.com
version: "2",
extension: false,
consumer_key: process.env.apikey,
consumer_secret: process.env.apisecret,
access_token_key: process.env.accesstoken,
access_token_secret: process.env.accesstokensecret,
};
module.exports = {
appConfig,
};
package.json
{
"name": "twitter_app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.0",
"express": "^4.17.3",
"path": "^0.12.7",
"twitter-lite": "^1.1.0"
}
}
There is no equivalent to the home timeline API in v2 - yet. This is on the roadmap. You’ll need to use the v1.1 API, or, be patient until a new version is available.
Related
the app displays and behaves perfectly on localhost but does not display at all once deployed on CPanel. I have deployed it on CPanel and run the command npm install from the GUI and I have run it also from the terminal using 'npm install -g npm-check-updates' followed by 'ncu -u'
I have tried to deploy the app the same way once more in case I made a mistake and get the same result. I don't understand why it does not seem to find 'app.get("/"'
app.js
var app = express();
var mysql = require("mysql"); // allow access to sql
var bodyParser = require("body-parser");
const path = require("path");
const VIEWS = path.join(__dirname, "views");
app.use(express.static("scripts"));
app.use(express.static("images"));
let index = 0;
var session = require("express-session");
var globalGallery = [];
let filter = false;
var lastSearchItem = "";
//var MySQLStore = require('express-mysql-session')(session);
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.set("view engine", "pug");
const db = mysql.createConnection({
host: "-------",
user: "------",
password: "--------",
database: "--------",
port: 3306,
});
db.connect((err) => {
if (err) {
throw err;
} else {
console.log("db connected!");
}
});
app.get("/", function (req, res) {
let sql = "select * FROM photo ORDER BY photoId DESC; ";
let query = db.query(sql, (err, gallery) => {
if (err) throw err;
globalGallery = gallery;
filter = false;
res.render("index", {
gallery: globalGallery,
});
});
});
index.pug
extends layout
block content
.maincontent
form(method="post" action="/filterphotos")
input.search(name="search", type="text", Placeholder="type 'ir' for example...")
button.searchbutton(type="submit") Search
.grid-container
each photo in gallery
- var text
- text = photo.photoPlace? photo.photoPlace : text
- text = photo.photoCountry? text+" "+photo.photoCountry : text
- text = photo.photoComments? text+" "+photo.photoComments : text
a.div.tooltip(href='/displayphoto/'+photo.photoId)
img.photothumbnail(src="http://isabellebidou.com/images/"+photo.photoThumbnail, alt=photo.photoThumbnail)
if text.length > 1
span.tooltiptext #{text}
package.json
{
"name": "isabellebidou.photos",
"version": "1.0.0",
"description": "photo website",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "photoapp"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"constantinople": "^4.0.1",
"express": "^4.17.1",
"express-session": "^1.17.1",
"jade": "^1.11.0",
"mysql": "^2.18.1",
"path": "^0.12.7",
"pug": "^3.0.0"
}
}
terminal screenshot
I am new to node js and postman and was working on this backend project to store a random persons details in my database. This is my app.js file:
var express=require("express");
var app=express();
//database
var mongoose=require("mongoose");
//connecting to database
mongoose.connect("mongodb+srv://mymongohost?retryWrites=true&w=majority",{ useNewUrlParser: true, useUnifiedTopology: true });
//creating user schema
var userSchema=new mongoose.Schema({
name:String,
age: String,
gender: String,
number: String,
location: String
});
var User =mongoose.model("user",userSchema);
//using body parser
var bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:true}));
//Creating a user
/*User.create({
name: "Snehan",
age: "30",
gender: "male",
number: "998899876",
location: "Sample address, near Thane, Mumbai,Mahasrashtra"
})*/
//ROUTES
app.get("/",function(req,res){
res.redirect("/user");
})
//sending all user data
app.get("/user", function(req,res){
User.find({}, function(err,user)
{
if(err)
res.send(err);
else
res.json(user);
})
})
//creating new user data
app.post("/user",function(req,res){
//storing the data received from body
var name=req.body.name;
var age=req.body.age;
var gender=req.body.gender;
var number=req.body.number;
var location=req.body.location;
//creating new object with all details
var newUser={
name:name,
age:age,
gender:gender,
number:number,
location: location
}
User.create(newUser,function(err,newlyCreatedUser){
if(err)
{res.send("Unable to create new user");}
else
{res.send(newlyCreatedUser);}
});
})
app.listen(process.env.PORT || 3000, function() {
console.log("Server started on port 3000");
});
Package.json:
{
"name": "userdetails",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^5.10.0"
}
}
However whenever im trying to test my code using postman,im unable to add a post a users data.
This was the post request I had sent. But the newlyCreated User object looks like:
{
"_id": "5f37ba449adfe112529f872a",
"__v": 0
}
Could anyone help me abt where im going wrong?
Your app is missing a json body-parser middleware, hence req.body is empty. Add the following line to your app-setup:
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
Your code is missing this:
app.use(bodyParser.json())
I'm new to APIs based on nodeJS and I would like to connect to an already existing collection in a MongoDB database.
If I try to access http://localhost:8080/teams I get an error on the browser: Cannot GET /Teams.
Not even the console.log get printed but nodemon (that I'm using to load after each save) shows no errors.
This is an example of the existing records:
use MYDB
db.TeamsCol.find()
{ "_id" : ObjectId("5d702df59ba60607dad06df4"), "teamID" : 1, "teamName" : "PT", "datetime" : "04-09-2019 10:21:16 Wednesday" }
{ "_id" : ObjectId("5d702ed59ba60607dad06df5"), "teamID" : 2, "teamName" : "ES", "datetime" : "01-09-2019 11:20:00 Sunday" }
I built the following struture:
project folder: API
API/server.js
API/models/teamModel.js
API/Routes/teamRouter.js
as described below:
API/server.js file:
// Import express
let express = require('express');
// Import Body parser
let bodyParser = require('body-parser');
// Import Mongoose
let mongoose = require('mongoose');
// Initialise the app
let app = express();
// Setup server port
var port = process.env.PORT || 8080;
// Import routes
let apiRouter = require("./Routes/teamRouter");
// Connecting to the database
const db = mongoose.connect('mongodb://localhost/MYDB', {useNewUrlParser: true});
// setting body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// API routes
app.use('/Teams', apiRouter);
// Running the server
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})
API/models/teamModel.js file:
// Import Mongoose
let mongoose = require('mongoose');
const Schema = mongoose.Schema;
const teamModel = new Schema({
teamID: { type: Number },
teamName: { type: String },
datetime: { type: String },
})
module.exports = mongoose.model('teamsModel', teamModel, 'TeamsCol');
API/Routes/teamRouter.js file:
// Import express
let express = require('express');
// Import Teams controller
var Team = require('../models/teamModel');
const teamRouter = express.Router();
teamRouter.route('/teams')
.get((req, res) => {
Console.log(req)
Team.find({}, (err, teams) => {
res.json(teams)
})
})
// Middleware
teamRouter.use('/:team', (req, res, next)=>{
Team.findById( req.params.team, (err,team)=>{
if(err)
res.status(500).send(err)
else {
req.team = team;
next()
}
})
})
teamRouter.route('/:team')
.get((req, res) => {
res.json(req.team)
}) // end get Teams/:team
// Export API routes
module.exports = teamRouter;
Here are the versions I'm using
mongo --version
MongoDB shell version v3.6.3
node --version
v8.9.4
and also the package.json contents:
{
"name": "teamsapi",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^5.6.12"
}
}
Any ideas?
Because in your server.js file, you already used:
app.use('/Teams', apiRouter);
So the api /teams doesn't exist, it should be /Teams/teams. And the full url will be http://localhost:8080/Teams/teams.
I'm trying to write a simple WebSocket server app based in Nodejs, but I am unable to get it started when I run npm run dev.
This is my package.json file:
"name": "lg-chain",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --watchAll",
"dev-test": "nodemon dev-test",
"start": "node ./app",
"dev": "nodemon ./app"
},
"keywords": [],
"license": "MIT",
"devDependencies": {
"jest": "24.1.0",
"nodemon": "1.18.9"
},
"dependencies": {
"body-parser": "1.18.3",
"crypto-js": "3.1.9-1",
"express": "4.16.4",
"ws": "6.1.3"
}
}
I developed both an http server and websocket server and my expectation is that they both will start when I run that command I mentioned above.
Below is my websocket server:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
class P2pServer {
constructor(blockchain) {
this.blockchain = blockchain;
this.sockets = [];
}
listen() {
const server = new Websocket.Server({ port: P2P_PORT });
server.on('connection', socket => this.connectSocket(socket));
this.connectToPeers();
console.log(`Listening for peer-to-peer connections on: ${P2P_PORT}`);
}
connectToPeers() {
peers.forEach((peer) => {
const socket = new Websocket(peer);
socket.on('open', () => this.connectSocket);
});
}
connectSocket(socket) {
this.sockets.push(socket);
console.log('Socket connected');
}
}
module.exports = P2pServer;
And this is my express server:
const express = require('express');
const bodyParser = require('body-parser');
const Blockchain = require('../blockchain');
const P2pServer = require('./p2p-server');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
const bc = new Blockchain();
const p2pServer = new P2pServer(bc);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/blocks', (req, res) => {
res.json(bc.chain);
});
app.post('/mine', (req, res) => {
const block = bc.addBlock(req.body.data);
console.log(`New block added: ${block.toString()}`);
res.redirect('/blocks');
});
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();
My express server starts up, but absolutely nothing happens with my websocket server. I don't get any errors anywhere. How do I begin troubleshooting this with websockets?
I'm taking an online course on writing block-chain from scratch.
The course utilizes javascript and node.js.
I am very new to these technologies but followed the course so far to the T.
i'm pasting the relevant code - the app file (index):
const express = require('express');
const bodyParser = require('body-parser');
const Blockchain = require('../blockchain');
const P2pServer = require('./p2p-server');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
const bc = new Blockchain();
const p2pServer = new P2pServer(bc);
app.use(bodyParser.json());
app.get('/blocks', (req, res) => {
res.json(bc.chain);
});
app.post('/mine', (req, res) => {
const block = bc.addBlock(req.body.data);
console.log(`New blovk added: ${block.toString()}`);
res.redirect('/blocks');
});
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();
and the code from p2p-server.js:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
//HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
class P2pServer {
constructor(blockchain) {
this.blockchain = blockchain;
this.sockets = [];
}
listen() {
const server = new Websocket.Server({ port: P2P_PORT });
server.on('connection', socket =>this.connectSocket(socket));
this.connectToPeers();
console.log(`listening to peer-to-peer connections on: ${P2P_PORT}`);
}
connectToPeers() {
peers.forEach(peer => {
const socket = new Websocket(peer);
socket.on('open', () => this.connectSocket(socket));
});
}
connectSocket(socket){
this.sockets.push(socket);
console.log('socket connected');
}
}
module.exports = P2pServer;
when I try to run the following in the command line:
HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
I get the following:
'HTTP_PORT' is not recognized as an internal or external command, operable program or batch file.
for some reason the process.env isn't picking up the input and passing it on to the app. What is wrong here?
Thanks!
EDIT: I was asked to add the package.json:
{
"name": "sf-chain",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --watchAll",
"dev-test": "nodemon dev-test",
"start": "node ./app",
"dev": "nodemon ./app"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^23.1.0",
"nodemon": "^1.17.5"
},
"dependencies": {
"body-parser": "^1.18.3",
"crypto-js": "^3.1.9-1",
"express": "^4.16.3",
"ws": "^5.2.0"
}
}
You are using:
$ HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
It is showing an error, because the window powershell will not recognize this command..
Instead you should use:
set HTTP_PORT=3002 && set P2P_PORT=5002 && set PEERS=ws://localhost:5001 && npm run dev
I believe were doing the same course. I'm sure you've probably figured this out but I tried the same step in Git Bash instead of Powershell and it worked.