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
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 recently changes my domain (and SSL certificate) on my live server and since then I have been not able to POST to my node.js express app.
GET is working perfectly fine and POST is working on localhost but my live app is returning a 404 error whenever I send a POST request.
Error stack trace shows:
Error: Not Found
at /opt/bitnami/apps/tot/app.js:63:15
at Layer.handle [as handle_request] (/opt/bitnami/apps/tot/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:317:13)
at /opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:335:12)
at next (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:275:10)
at allowCrossDomain (/opt/bitnami/apps/tot/app.js:56:5)
at Layer.handle [as handle_request] (/opt/bitnami/apps/tot/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:317:13)
at /opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:335:12)
at next (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/opt/bitnami/apps/tot/node_modules/serve-static/index.js:121:7)
at SendStream.emit (events.js:200:13)
at SendStream.error (/opt/bitnami/apps/tot/node_modules/send/index.js:270:17)
at SendStream.onStatError (/opt/bitnami/apps/tot/node_modules/send/index.js:421:12)
I have a very simple app:
require('dotenv').config();
const express = require('express');
const app = express();
const helmet = require('helmet');
//const morgan = require('morgan'); //logging requests to console
//const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const path = require('path');
const startupDebugger = require('debug')('tot:startup');
const mongoDebugger = require('debug')('tot:mongo');
const port = process.env.WEB_PORT;
// configure middleware
app.set('port', process.env.port || port); // set express to use this port
//app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
app.set('view engine', 'ejs'); // configure template engine
app.use(helmet());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // parse form data client
app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
//app.use(fileUpload()); // configure fileupload
const urlencodedParser = bodyParser.urlencoded({ extended: false })
// --- Routes ---
const {getHomePage} = require('./routes/index');
const {playground} = require('./routes/playground');
const {getMessage} = require('./routes/slack/events-api');
const {getComponent} = require('./routes/slack/interactive-components');
const {renderSurvey} = require('./routes/feedback/survey');
const {score} = require('./routes/feedback/score-api');
app.get('/', getHomePage);
app.get('/playground', playground);
// Slack APIs
app.post('/slack/events-api', getMessage);
app.post('/slack/interactive-components', urlencodedParser, getComponent);
//Feedback
app.get('/feedback/survey/:team_id/:user_id/:question_id/:date', renderSurvey);
app.post('/feedback/score', score);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
console.error(err.stack);
next(err);
});
app.listen(port, () => { startupDebugger(`Server running on port: ${port}`); });
mongoose.connect(process.env.MONGO, { useNewUrlParser: true })
.then(() => mongoDebugger('Connected to MongoDB.'))
.catch(error => mongoDebugger('MongoDB Error: '+error));
Here is an example for /slack/events-api
getMessage: async function (req, res) {
//console.log(req);
let payload = req.body;
console.log('Payload:');
console.dir(payload, {depth: null});
slackDebugger('Slack Event API Challange Request');
res.render('slack/events-api.ejs', {
title: "Slack Bot"
, output: req.body.challenge
});
}
}
When I post via Postman locally it works fine:
[nodemon] starting `node app.js`
tot:startup Server running on port: 3000 +0ms
tot:mongo Connected to MongoDB. +0ms
Payload:
{ token: 'Jhj5dZrVaK7ZwHHjRyZWjbDl',
challenge: '3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P',
type: 'url_verification' }
tot:slack Slack Event API Challange Request +0ms
On the live server:
[nodemon] starting `node app.js`
tot:startup Server running on port: 3000 +0ms
tot:mongo Connected to MongoDB. +0ms
Error: Not Found
at /opt/bitnami/apps/tot/app.js:63:15
at Layer.handle [as handle_request] (/opt/bitnami/apps/tot/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:317:13)
at /opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:335:12)
at next (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:275:10)
at allowCrossDomain (/opt/bitnami/apps/tot/app.js:56:5)
at Layer.handle [as handle_request] (/opt/bitnami/apps/tot/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:317:13)
at /opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:335:12)
at next (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/opt/bitnami/apps/tot/node_modules/serve-static/index.js:121:7)
at SendStream.emit (events.js:200:13)
at SendStream.error (/opt/bitnami/apps/tot/node_modules/send/index.js:270:17)
at SendStream.onStatError (/opt/bitnami/apps/tot/node_modules/send/index.js:421:12)
I cannot for the life of me work out why this has suddenly stopped working on live since updating the live URL/SSL.
If anybody can point me in the right direction that would be amazing.
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
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. :)