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
Related
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())
In an Express controller function, I am running into to this error Error [ERR_HTTP_HEADERS_SENT]. This occurs when I call res.json() if headers have already been set on the res object. However, I don't see place in my function (or middleware) where headers could be set prior to my calling res.json().
To debug the cause of this error, I thought I could add some logging. Prior to calling res.json, I could check if headers had been set and, if so, log some information about who set them.
async function get(req, res) {
...
if (res._header) {
logger.debug(...);
}
res.json(...);
Unfortunately, I don't see anything useful in the res object to log, any message that would indicate why/how the headers were set (or who set them). Any suggestions for what I could log to debug this issue? Or other debugging suggestions?
You can patch res.header res.send res.set to log the stack trace for you. For example this is my main application.
const express = require('express');
const app = express();
const someGoody = require('./stupid-blackbox');
/** patch the res **/
app.use((req, res, next) => {
const _header = res.header.bind(res); // .header and .set is an alias pair
const _send = res.send.bind(res);
res.header = res.set = (field, val) => {
console.trace('.header/.set called', field, val);
console.log('-----');
return _header(field, val);
}
res.send = (body) => {
console.trace('.send called', body);
console.log('-----');
return _send(body);
}
next();
})
// some innocent looking middleware
app.use(someGoody);
// my main routes
app.get('*', (req, res) => {
res.json({url: req.url});
})
app.listen(3000);
And for stupid-blackbox.js:
const express = require('express');
const router = express.Router();
router.use((req, res, next) => {
res.header('X-Crash-You', '1').send(':)');
next();
})
module.exports = router;
When ran, you will get this in the log:
Trace: .header/.set called X-Crash-You 1
at ServerResponse.res.header.res.set (C:\Users\eric_\Desktop\initial\play\index.js:11:13)
at router.use (C:\Users\eric_\Desktop\initial\play\stupid-blackbox.js:6:9)
at Layer.handle [as handle_request] (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:317:13)
at C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\layer.js:95:5)
-----
Trace: .send called :)
at ServerResponse.res.send (C:\Users\eric_\Desktop\initial\play\index.js:17:13)
at router.use (C:\Users\eric_\Desktop\initial\play\stupid-blackbox.js:6:36)
at Layer.handle [as handle_request] (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:317:13)
at C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\eric_\Desktop\initial\play\node_modules\express\lib\router\layer.js:95:5)
On the second line of each stack trace you can see the stupid-blackbox.js.
On a side note, res.json will not result in error if only res.header or res.set is called, the error is headers has been sent so that means somewhere in the code, res.send is called causing headers to be sent before your actual code.
I am beginner in Nodejs program I tried to do simple cookies program.I successfully set and delete the cookies successfully.but I could not get the cookies what I set before.It shows an error.can anyone tell me how to get the cookie in nodejs Thanks in advance....
const express=require("express");
const cookieParser=require("cookie-parser");
const app=express();
const router=express.Router();
const port=process.env.Port||8086;
app.use(router);
app.use(cookieParser());
router.get("/setcookie",function(req,res)
{
console.log("Come in to set the cookie");
res.cookie("program","NodeJS"/*,{maxAge:60000}*/);
res.cookie("Database","MongoDB"/*,{maxAge:1200000}*/);
console.log("Cookie set successfully");
res.send("Cookie set successfully");
});
router.get("/deletecookie",function(req,res)
{
console.log("come in to delete the cookie");
res.clearCookie("program");
res.send("Cookie deleted successsfully");
});
router.get("/getcookie",function(req,res)
{
console.log("Come in to read the cookie");
console.log(req.cookies['program']);
console.log(req.cookies['Database']);
res.send("Cookie Accessed successfully");
});
app.listen(port,function()
{
console.log("server is listening on port 8086");
});
ERROR I GOT:
TypeError: Cannot read property 'program' of undefined
at C:\Users\VIGNESH\WebstormProjects\cookies-middleware\simple-cookies.js:25:28
at Layer.handle [as handle_request] (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:47:12)
You need to add the cookieParser() before the router, so the code will be
app.use(cookieParser());
app.use(router);
Because otherwise the control is not even getting into cookieParser
Trying to setup routes based on an array of objects in ExpressJS, but I'm getting an error when attempting to access the route.
The error is this:
TypeError: shares[Symbol.iterator] is not a function
at router
(C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\routes\shares.js:10:18)
at Layer.handle [as handle_request] (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:317:13)
at C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:317:13)
at C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:284:7
from code like this:
var router = (shares) => {
for(let share of shares){
shareRouter.route(`/${share.name}`)
.get((req, res) => {
var fileList = [];
fs.readdir(share.location, (err, files) => {
for(let file in files){
fileList.push(file);
shareRouter.route(`/${file}`)
.get((req, res) => {
var filePath = path.join(share.location, file);
res.download(filePath, `${file}`);
});
}
}).then(()=>{
res.render('shareFiles', fileList);
});
});
}
};
shares is defined prior to the router function call. What's supposed to happen is that when the application starts, it looks in the config file, imported earlier, get's the list of folders to share and sets them up based on the name property of the object, then goes through each of the files in the folder to create routes based on their file names, which is then passed into a pug template that provides links to the file routes.
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) {