Facebook Messenger API: Can't Get POST Requests - node.js

I followed steps which in this page
https://developers.facebook.com/docs/messenger-platform/quickstart
My nodejs codes
app.post('/webhook/', function(req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, "Text received, echo: ");
}
}
res.sendStatus(200);
});
And I get an error like this
TypeError: Cannot read property 'entry' of undefined
at /home/user/public_html/app/testbot/webhook.js:31:30
at Layer.handle [as handle_request] (/home/user/public_html/app/testbot/node_modules/express/lib/router/layer.js:95:5)
at next (/home/user/public_html/app/testbot/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/home/user/public_html/app/testbot/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/user/public_html/app/testbot/node_modules/express/lib/router/layer.js:95:5)
at /home/user/public_html/app/testbot/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/home/user/public_html/app/testbot/node_modules/express/lib/router/index.js:330:12)
at next (/home/user/public_html/app/testbot/node_modules/express/lib/router/index.js:271:10)
at serveStatic (/home/user/public_html/app/testbot/node_modules/express/node_modules/serve-static/index.js:74:16)
at Layer.handle [as handle_request] (/home/user/public_html/app/testbot/node_modules/express/lib/router/layer.js:95:5)
I can't get POST requests which coming from Facebook. How can I solve that?

I was stuck before with the same problem. You need to use the body-parser lib:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json();
then pass it to the post hook
app.post('/webhook/', jsonParser, function(req, res) {

Related

Express - Cannot access 'Database' before initialization

const express = require('express');
const upload = require("express-fileupload");
const editJsonFile = require("edit-json-file");
const fs = require('fs');
const app = express();
app.use(upload())
app.use(express.urlencoded({ extended: true }))
const playlist = editJsonFile(`${__dirname}/playlist.json`);
app.post("/upload", (req, res) => {
//Save file from the html form to ./mp3
var file = req.files.file;
req.pipe(fs.createWriteStream("./mp3/" + file.name));
res.send("File uploaded");
playlist.append("playlist", file.name)
playlist.save()
}),
app.get("/playlist", (req, res) => {
console.log(playlist.get("playlist"))
let playlist = playlist.get("playlist")
let html = "";
for (let i = 0; i < playlist.length; i++) {
html += `<br>${playlist[i]}`;
}
res.send(html);
}),
Hey,
Im trying to make a music player, but somehow I get the error:
ReferenceError: Cannot access 'playlist' before initialization
at C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\index.js:20:17
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:346:12)
at next (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:280:10)
at urlencodedParser (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\body-parser\lib\types\urlencoded.js:91:7)
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
I can write to the Database without any issues, but when I try to read from it I get the error above, what can I do?
app.get("/playlist", (req, res) => {
console.log(playlist.get("playlist"))
let playlist = playlist.get("playlist")
The second line console.log(playlist.get("playlist")) is trying to print the playlist variable but its declared in the next line, hence no access to that particular variable ergo the error. You can only access something after it has been initialized.
I think you are overwriting the playlist variable. The file is playlist and when you get the element you assign it to playlist as well
Also, a file is not a database

req.headers.cookie is undefined

Whenever I run my program, this happens:
TypeError: Cannot read property 'toString' of undefined
at /home/runner/Factions-Online-Multiplayer-Clicker-Game/index.js:28:49
at Layer.handle [as handle_request] (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/layer.js:95:5)
at next (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/layer.js:95:5)
at /home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/index.js:335:12)
at next (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/index.js:275:10)
at expressInit (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/layer.js:95:5)
I've done this before, but I'm not sure why it returns this. The code where the error happens is below.
app.get("/", (req, res) => {
var cookies = cookie.parse(req.headers.cookie.toString());
var accounts = loadjson('passwords.json');
if (cookies.username && cookies.password) {
if (cookies.username in accounts) {
if (accounts[cookies.username] === sha256(cookies.password)) {
res.render("html/game")
} else {
res.render("html/index");
}
} else {
res.render("html/index");
}
} else {
res.render("html/index");
}
});
The full program is here.
When you use cookie-parser package as a middleware it returns cookie in req.cookies object rather than req.headers.cookie.
app.get("/", (req, res) => {
var cookies = cookie.parse(req.cookies.toString());
//... Rest of the code
}
Read more about it here

while inserting data to database using postman showing error in controller file

while using node.js i am not able to insert a data to database ,i am using express.js ,mongoose but getting error which i mentioned in code as comment
Blockquote
error is
Blockquote
TypeError: Cannot read property 'name' of undefined
at insert (E:\node\website\controller\signup.js:5:25)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at next (E:\node\website\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\node\website\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at E:\node\website\node_modules\express\lib\router\index.js:281:22
at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
at Function.handle (E:\node\website\node_modules\express\lib\router\index.js:174:3)
at router (E:\node\website\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
at E:\node\website\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
at expressInit (E:\node\website\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
at E:\node\website\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
at query (E:\node\website\node_modules\express\lib\middleware\query.js:45:5)
Blockquote
//controller file named as signup.js
var express=require('express');
var post1=require('../model/singup')
var router=express.Router();
var insert=(req,res)=>{
var name1= req.body.name;// error:name is not defined
var email1= req.body.email;//error:email is not defined
var password1= req.body.password;//error:password is not defined
post1.create({
name: name1,email:email1,password:password1
},(err,result)=>{
if(err){res.json({message:'error'
})
}
else{res.json({message:'sucessful',result:result
})
}
})
}
router.post('/signup',insert);
router.get('/h',(req,res)=>{
res.json({
message:'insert'
})
console.log("insert");
})
module.exports=router;
Blockquote
//model file named as signup.js
require('../db');
var mongoose=require('mongoose');
mongoose.Promise=require('bluebird');
var schema= new mongoose.Schema({
name:{type:String,required:true},
email:{type:String,required:true},
password:{type:String,required:true},
},
{timestamp:true});
module.exports=mongoose.model('post1',schema);
Blockquote
//db.js file for database connection
var mongose=require('mongoose');
mongose.set('useNewUrlParser', 'true');
mongose.set('useCreateIndex', 'true');
mongose.set('useFindAndModify', 'true');
mongose.connect("mongodb://127.0.0.1:27017/website");
var db=mongose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',(req,res)=>{
console.log("connected with db!!!");
})
Blockquote
//index.js
var app=require('./server')
var signup=require('./controller/signup')
var session=require('express-session')
app.set('viewengin','ejs')
app.set('useNewUrlParser', 'true')
app.set('useUnifiedTopology', 'true')
app.use('/user',signup)
app.use(session({
secret:'keyboard cat ',
resave:false,
cookies:{
secrue:true
},
}))
app.all('*',(req,res)=>{
return res.json({status: 205,message: 'not found'});
})
var server=app.get('/',(req,res)=>{
req.end()
});
Seems you are missing the body-parser middleware.
$ npm i body-parser
var express=require('express');
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

TypeError using the jwt-express package

I just tried to work with the JWT-Express package for NodeJS in order to create a JWT token when a user wants to log in. Unfortunately, I receive a TypeError with the package.
Following my code:
var express = require('express');
var app = express();
var jwt = require('jwt-express');
app.use(jwt.init('secret'));
app.get('/login', function(req, res) {
var user = {
first: "Firstname",
last: "Lastname",
is_admin: true
};
// we are using cookies so the JWT is
// automatically stored for us
var jwt = res.jwt({
admin: user.is_admin,
name: user.first + ' ' + user.last
});
// we now have access to the JWT Object
console.log(jwt);
// if we weren't using cookies, we could
// now send the token to the client
res.send(jwt.token);
});
app.listen(8080);
I verified that both the object jwt in line 3 and the call to jwt.init returns something unequal to undefined.
The error seems to stick somehow in the package internally. The system crashes even before the GET requests is being processed.
The error is:
TypeError: Cannot read property 'jwt-express' of undefined
at Object.<anonymous> (/Users/stuckenholz/auth/node_modules/jwt-express/jwt-express.js:218:36)
at Layer.handle [as handle_request] (/Users/stuckenholz/auth/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:317:13)
at /Users/stuckenholz/auth/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:335:12)
at next (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:275:10)
at expressInit (/Users/stuckenholz/auth/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/Users/stuckenholz/auth/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:317:13)
at /Users/stuckenholz/auth/node_modules/express/lib/router/index.js:284:7
Any ideas?
Best regards...
I had the same error and it happened that I had forgotten to include jwt options.
This solved it for me:
options = { cookies: false }
app.use(jwt.init('secret', options))
I am not using cookies
It looks like the req.cookies is empty at line 218:
token = req.cookies[this.options.cookie];
Don't forget to parse the cookies before initializing jwt-express:
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
https://github.com/expressjs/cookie-parser

node.js TypeError: undefined is not a function on app.get("/")

I'm trying out node.js and some hello world examples and I'm getting this error
TypeError: undefined is not a function
at c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\server.js:10:13
at Layer.handle [as handle_request] (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\layer.js:95:5)
at next (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\layer.js:95:5)
at c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\index.js:277:22
at Function.process_params (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\index.js:330:12)
at next (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\index.js:271:10)
at expressInit (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\middleware\init.js:33:5)
at Layer.handle [as handle_request] (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\layer.js:95:5)
Here's my code
var http = require("http");
var express = require("express");
var app = express();
app.get("/",
function(res, req) {
res.send("<html><body><h1>Express</h1></body></html>");
});
app.get("/api/users",
function(req, res) {
res.send({ name: "Louis", isValid: true, group: "Admin" });
});
var server = http.createServer(app);
server.listen(3000);
I'm only getting the error when I hit http://localhost:3000/
I do not get any error when I hit http://localhost/api/users
problem in a ordering of parameter.. req object doesn't have any send function.
var http = require("http");
var express = require("express");
var app = express();
app.get("/",
function(req, res) {
res.send("<html><body><h1>Express</h1></body></html>");
});
app.get("/api/users",
function(req, res) {
res.send({ name: "Louis", isValid: true, group: "Admin" });
});
var server = http.createServer(app);
server.listen(3000);
Your function for app.get("/") is not correct. The order in which you have passed the arguments is not right. The correct way is to first give request object and then the response object. The correct way is to write like this:
app.get("/",
function(req, res) {
res.send("<html><body><h1>Express</h1></body></html>");
});
Hope this might work for you. :)

Resources