I am getting the following error while posting the data via REST API through Postman using Node.js. I am providing my code below.
server.js:
var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var app=express();
var server=http.Server(app);
var port=8080;
require('./route/route.js')(app);
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json({limit: '5mb'})) // parse application/json
app.use(methodOverride()); // simulate DELETE and PUT
app.get('/',function(req,res){
res.json({"message": "Task management application."});
})
server.listen(port);
console.log("Server is running on the port"+port);
route/route.js:
var task=require('../controller/controller.js');
module.exports = function(app) {
app.post('/signup',task.userSignup);
}
controller/controller.js:
var mongoJs=require('mongojs');
var database='TASK';
var collections=['f_users'];
var db=mongoJs("127.0.0.1:27017/"+database, collections);
db.on('connect', function () {
console.log('database connected')
});
exports.userSignup=function(req,res){
console.log('req',req);
var username=req.body.username;
var password=req.body.password;
var phone=req.body.phone;
db.f_users.insert({'username':username,'password':password,'phone':phone},function(err,docs){
if (!err) {
if (docs) {
res.json({'message':'User has registered successfully'});
}
}
})
}
I am doing the post like below.
Here I am getting the following error while posting the data.
TypeError: Cannot read property 'username' of undefined
<br> at exports.userSignup (C:\xampp\htdocs\bigdata\controller\controller.js:10:23)
<br> at Layer.handle [as handle_request] (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\layer.js:95:5)
<br> at next (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\route.js:131:13)
<br> at Route.dispatch (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\route.js:112:3)
<br> at Layer.handle [as handle_request] (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\layer.js:95:5)
<br> at C:\xampp\htdocs\bigdata\node_modules\express\lib\router\index.js:277:22
<br> at Function.process_params (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\index.js:330:12)
<br> at next (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\index.js:271:10)
<br> at expressInit (C:\xampp\htdocs\bigdata\node_modules\express\lib\middleware\init.js:33:5)
<br> at Layer.handle [as handle_request] (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\layer.js:95:5)
How can I resolve this error and save the data successfully?
Related
I tried to get the data from a nested array but ended up getting the error type error cannot read property "value" of undefined, I don't know If I calling back in a wrong way but I end up getting the output in console along with the error
const express = require('express');
const app = express();
var bodyParser = require('body-parser');
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
var entries = [{name:"", address:"", month:"", year:""}];
app.get("/", function(req, res){
res.render("homepage");
});
app.get("/addentry", function(req, res){
res.render("add");
});
app.post("/add", function(req, res){
var input = req.body;
var newEntry = {name: input.name, address: input.address, month: input.month, year: input.year};
entries.push(newEntry);
res.redirect("/addentry");
});
app.post("/search", function(req, res){
var search = req.body;
for(var i = 0; i <= entries.length; i++){
console.log(entries[i].name);
}
res.redirect("/addentry");
});
app.listen(3000, function(){
console.log("Server Started Successfully");
});
I end up getting this error always
TypeError: Cannot read property 'name' of undefined
at C:\AllNodeProjects\globalledger\app.js:29:36
at Layer.handle [as handle_request] (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\layer.js:95:5)
at next (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\layer.js:95:5)
at C:\AllNodeProjects\globalledger\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\index.js:335:12)
at next (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\index.js:275:10)
at C:\AllNodeProjects\globalledger\node_modules\body-parser\lib\read.js:130:5
at invokeCallback (C:\AllNodeProjects\globalledger\node_modules\raw-body\index.js:224:16)
You need to add app.use(bodyParser.json()); after this line => app.use(bodyParser.urlencoded({ extended: true }));
I am trying to set up neo4j databace to use with javescript code.
When I run my code, I keep getting this
PS C:\Users\futur\Documents\Coding\Neo4j> node app.js body-parser
deprecated undefined extended: provide extended option app.js:21:20
Server has started GET / 304 37.114 ms - - { Neo4jError: getaddrinfo
ENOTFOUND locthost locthost:7687
at captureStacktrace (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\result.js:200:15)
at new Result (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\result.js:73:19)
at Session._run (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\session.js:122:14)
at Session.run (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\session.js:101:19)
at C:\Users\futur\Documents\Coding\Neo4j\app.js:31:4
at Layer.handle [as handle_request] (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\index.js:281:22
code: 'ServiceUnavailable', name: 'Neo4jError' }
Here is what my code looks like
var express = require("express");
var path = require("path");
var logger = require("morgan");
// var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var neo4j = require("neo4j-driver").v1;
var app = express();
//
// <script src="lib/browser/neo4j-web.min.js"></script>
//view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extened: false}));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
var driver = neo4j.driver("bolt://locthost", neo4j.auth.basic("neo4j", "test"));
var session = driver.session();
//home route
app.get('/', function(req, res){
session
.run("MATCH (n) RETURN n")
.then(function(result){
result.records.forEach(function(records){
console.log(records._fields[0]);
});
})
.catch(function(error){
console.log(error);
});
res.render("index");
});
app.listen(3000);
console.log('Server has started');
module.export = app;
What do I need to do?
You may have a typo in your bolt URI.
If your code is running on the same machine as the neo4j server, try changing locthost to localhost.
I am new to node and need some help in using session. I am using EJS to render my web-pages. Please find my code below.
app.js
var express = require('express');
var registerController = require('./controllers/registerController');
var app =express();
var bodyParser = require('body-parser');
var sessions=require('express-session');
app.set('view engine', 'ejs');
app.use(express.static('./public'));
app.use(sessions({
secret:'asasds*(&^*(',
resave:false,
saveUninitialized:true
}));
app.use(function(req, res, next) {
res.locals.user = req.session.user;
next();
});
//controllers
registerController(app);
app.listen(3000);
console.log( " you are listening to port 3000");
registercontroller.js
var bodyParser = require('body-parser');
var fs = require('fs');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
module.exports=function(app){
app.get('/register',function(req,res){
res.render('register');
});
app.post('/register',urlencodedParser,function(req,res){
console.log(" inside controller :::" );
var userObj = {
"username":req.body.username,
"password":req.body.password,
"email":req.body.email,
"fNmame":req.body.fNmame,
"lNmame":req.body.lNmame
}
console.log(" userObj :::" + JSON.stringify(userObj));
fs.writeFile("/assets/data.txt", JSON.stringify(userObj), function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
var val = req.session.user;
res.render('index2',{session: req.session});
});
};
index2.ejs
<%= JSON.stringify(session) %>
Using all the above I get the below error
<%= JSON.stringify(session) %>
session is not defined
at eval (eval at compile (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:524:12), <anonymous>:24:41)
at returnedFn (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:555:17)
at tryHandleCache (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:203:34)
at View.exports.renderFile [as engine] (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:412:10)
at View.render (c:\learning\socialnetworking\node_modules\express\lib\view.js:128:8)
at tryRender (c:\learning\socialnetworking\node_modules\express\lib\application.js:640:10)
at EventEmitter.render (c:\learning\socialnetworking\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (c:\learning\socialnetworking\node_modules\express\lib\response.js:971:7)
at c:\learning\socialnetworking\controllers\registerController.js:26:13
at Layer.handle [as handle_request] (c:\learning\socialnetworking\node_modules\express\lib\router\layer.js:95:5)
at next (c:\learning\socialnetworking\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (c:\learning\socialnetworking\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\learning\socialnetworking\node_modules\express\lib\router\layer.js:95:5)
at c:\learning\socialnetworking\node_modules\express\lib\router\index.js:281:22
at Function.process_params (c:\learning\socialnetworking\node_modules\express\lib\router\index.js:335:12)
at next (c:\learning\socialnetworking\node_modules\express\lib\router\index.js:275:10)
res.render('register.ejs', {
layout:false,
session: req.session
});
you need to include this basically
I tried connecting it with mlab database but its not working, went through a lot of stackoverflow answers and tried everything but the errors are still there, please help.
var express = require('express');
var mongojs = require('mongojs');
var mongodb = require('mongodb');
// var db = mongojs('contactlist',['contactlist']);
var uri = 'mongodb://user:pass#####.mlab.com:13702/contactlist'
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, contactlist) {
});
var db = mongodb.connect(uri);
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/contactlist', function(req, res){
console.log("I received a GET request");
db.contactlist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/contactlist', function(req, res) {
console.log(req.body);
db.contactlist.insert(req.body,function(err,doc) {
res.json(doc);
});
});
app.listen(process.env.PORT ||3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
I am getting these errors after I try inserting data on the browser, its not even displaying the data from the database.
Errors:
TypeError: Cannot read property 'find' of undefined
at D:\contactlistapp\server.js:17:16
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
at next (D:\contactlistapp\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\contactlistapp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
at D:\contactlistapp\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\contactlistapp\node_modules\express\lib\router\index.js:335:12)
at next (D:\contactlistapp\node_modules\express\lib\router\index.js:275:10)
at jsonParser (D:\contactlistapp\node_modules\body-parser\lib\types\json.js:103:7)
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
{ name: 'kkm', email: 'kmk' }
TypeError: Cannot read property 'insert' of undefined
at D:\contactlistapp\server.js:27:16
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
at next
db.[collection_name] syntax ( ie. collection name on property ) is supported in MongoShell, but in node environment you must use following syntax:
db.collection("collection_name").find(). The same with insert.
Also note that connect function of MongoClient is async. You must get reference to database from callback that you specified.
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, contactlist) {
db = contactlist;
});
External service makes a request to my application , and the POST request body encoding winows- 1251 , but as I understand it , body-parser does not work with windows-1251, and i get a error
POST /api/v1/payment/result 415 76.170 ms - 3073
UnsupportedMediaTypeError: unsupported charset "WINDOWS-1251"
at urlencodedParser (/home/keler/ask-landing/node_modules/body-parser/lib/types/urlencoded.js:102:12)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/keler/ask-landing/node_modules/express/lib/router/index.js:330:12)
at next (/home/keler/ask-landing/node_modules/express/lib/router/index.js:271:10)
at jsonParser (/home/keler/ask-landing/node_modules/body-parser/lib/types/json.js:107:37)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/keler/ask-landing/node_modules/express/lib/router/index.js:330:12)
at next (/home/keler/ask-landing/node_modules/express/lib/router/index.js:271:10)
at logger (/home/keler/ask-landing/node_modules/morgan/index.js:144:5)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/keler/ask-landing/node_modules/express/lib/router/index.js:330:12)
at next (/home/keler/ask-landing/node_modules/express/lib/router/index.js:271:10)
at expressInit (/home/keler/ask-landing/node_modules/express/lib/middleware/init.js:33:5)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/keler/ask-landing/node_modules/express/lib/router/index.js:330:12)
at next (/home/keler/ask-landing/node_modules/express/lib/router/index.js:271:10)
at query (/home/keler/ask-landing/node_modules/express/lib/middleware/query.js:49:5)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
Prompt decision
I bring your own code .
in App
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var bb = require('express-busboy');
var routes = require('./routes/index');
var app = express();
// view engine setup
var engines = require('consolidate');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../client')));
bb.extend(app);
require("./config/db.js")();
app.use('/', require('./routes'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var server = app.listen(3000, function() {
console.log('Express server listening on port ' + server.address().port);
});
module.exports = app;
in Route
var payment = {
result : function(req, res, next) {
console.log(req.body);
res.send("ok");
}
}
module.exports = payment;