I am making a post request using Restlet client tool in chrome. In console.log(res), I can clearly see that there is body present there with totally correct data but still I am always getting an error message saying body is undefined when doing res.body.
Here is the code
var express = require('express');
var parser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(parser.urlencoded({extended: true}));
app.use(parser.json());
var db = mongoose.connection;
var port = process.env.PORT || 8000;
var router = express.Router();
router.use(function(req, res, next) {
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/',function(req,res){
res.json({msg: 'Welcome to Pre-Health API!'});
});
var User = mongoose.Schema({
first_name: String,
last_name: String
},{
collection: 'User',
timestamps: true
});
router.route('/user').post(function(res,req) {
var user = mongoose.model('user',User);
console.log(req);
var new_user = new user({
first_name: req.body.first_name,
last_name: req.body.last_name
});
user.save(function(err) {
if(err) res.send(err);
res.json({message: "User created"});
});
});
app.use('/api',router);
app.listen(port);
console.log('API Listening on port: ' + port);
In the function you have req and res inverted, it should be:
router.route('/user').post(function(req, res) { ...
Related
I'm learning Node.js and I'm finding some troubles with redirecting the user to an :id path. I would like to print there his username.
So to make an overview it is a landing page with a form where I ask for an Alias and an email. When user clicks submit I'd like to move him to /:id path to print its' username.
My code is the following:
var express = require("express"),
app = express(),
request = require("request"),
mongoose = require("mongoose"),
bodyParser = require("body-parser");
app.set("view engine", "ejs")
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect("mongodb://localhost/Scape_Room", {useNewUrlParser: true, useUnifiedTopology: true});
var userSchema = new mongoose.Schema({
email: String,
alias: String,
});
var user = mongoose.model ("user",userSchema);
app.get("/", function(req, res){
res.render("index")
})
app.post("/newuser", function(req,res){
var name = req.body.name;
var email = req.body.email;
var newUser = {name:name, email:email}
user.create(newUser, function(err,newlyUser){
if(err){
console.log(err)
} else {
res.redirect("/start/:id")
}
})
})
app.get("/start/:id", function(req,res){
user.findById(req.params.id, function(err, foundUser){
if(err){
console.log(err)
} else{
res.render("startPoint", {user:foundUser})
}
})
})
app.listen(3000, function(err){
console.log("Server listening")
})
error is the following: { CastError: Cast to ObjectId failed for value ":id" at path "_id" for model "user"
I've tried:
- to change the path to :_id
- added start/ into the route
When you are using the redirect() method, you must pass a real route url not an id.
const express = require("express")
const request = require("request");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
app.set("view engine", "ejs")
app.use(express.static("public"));
mongoose.connect("mongodb://localhost/Scape_Room", { useNewUrlParser: true, useUnifiedTopology: true });
const userSchema = new mongoose.Schema({
email: String,
alias: String,
});
const user = mongoose.model("user", userSchema);
app.get("/", function (req, res) {
res.render("index");
});
app.post("/newuser", function (req, res) {
const { name, email } = req.body;
if (!name || !email) {
return res.end();
}
const newUser = { name: name, email: email }
user.create(newUser, function (err, newlyUser) {
if (err) {
console.log(err);
return res.end();
}
if (!newlyUser) {
console.log("Couldn't save user!");
return res.end();
}
if (!newlyUser.id) {
console.log("No user id found");
return res.end();
}
res.redirect(`/start/${newlyUser.id}`);
});
});
app.get("/start/:id", function (req, res) {
user.findById(req.params.id, function (err, user) {
if (err) {
console.log(err);
} else {
res.render("startPoint", { user });
}
})
})
app.listen(3000, function (err) {
console.log("Server listening")
});
Use something like below
app.post("/newuser", function(req,res){
var name = req.body.name;
var email = req.body.email;
var newUser = {name:name, email:email}
user.create(newUser, function(err,newlyUser){
if(err){
console.log(err)
} else {
res.redirect(`/start/${newlyUser._id}`)
}
})
})
This photo shows --ms-- message. And in client side, I get timeout error.
I am trying to figure out where it occurs and why using try-catch and console.log but I can't find any.
This is 'routes/email.js'
var express = require('express');
var router = express.Router();
var db = require('../db');
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'ssssss#gmail.com',
pass: 'SSSSSS'
}
});
router.get('/send', function(req, res, next) {
console.log('/send');
var email = decodeURI(req.query.to);
console.log(email);
var rand = Math.floor((Math.random() * 9000 + 1000));
var link="http://"+req.get("host")+"/email/verify?email="+email+"&num="+rand;
var mailOptions={
to : email,
subject : "Please confirm your Email account",
html : "Hello,<br> Please Click on the link to verify your email.<br>Click here to verify"
}
try{
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.json({result:false,message:"Incorrect email", code:404});
}else{
console.log("Message sent:\n"+JSON.stringify(response, null, 2));
try{
console.log(JSON.stringify(db, null, 2));
var sql = "INSERT INTO email_verification(email, code) VALUES(?,?)";
var input = [email, rand];
db.get().query(sql, input, function(err, result){
if(err) res.json({result:false, message:"SQL error", code:403});
res.json({result:true, message:"Please check your email.", code:100});
});
// res.json({result:false, message:"DB ERROR", code:401});
}catch(e){
console.log(e);
}
}
});
}catch(e){
console.log(e);
}
});
module.exports = router;
db.get().query() part doesn't execute at all.
This is db.js.
const mariadb = require('mariadb');
var pool;
exports.connect = function(done){
console.log("Trying to connect DB...");
pool = mariadb.createPool({
host: 'localhost',
user: 'root',
password: 'ssss',
database:"SSSS",
connectionLimit: 100
});
}
exports.get = function(){
console.log("exports.get");
return pool;
}
The console.log("exports.get"); parts works fine.
This is app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var db = require('./db');
//var passport = require('./passport');
//var auth = require('./routes/auth');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
db.connect(function(err){
console.log(err);
if(err){
console.log('Unable to connect to MariaDB.');
process.exit(1);
}
});
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', require("./routes/index"));
app.use('/email', require("./routes/email"));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(404);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I just used this db.jsand app.js file from my other project and it worked fine there. But I don't know why this time I have this problem.
Which part and why I am having this problem and how can I fix it?
It'd be easier to work with node.js if I can track the error easily. Figuring out the problematic part takes lots of time. Is there any module or tool for that?
I am trying to set up a MEAN (mongodb, express, nodejs, angular6(CLI)) app. Trying to post user signup form data to mongo database, but its throwing an error. It is my first MEAN app, trying to learn.
Do I miss something here?
Error: Route.post() requires callback functions but got a [object Undefined]
server.js
Here is server.js file.
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var app = express();
var api = require('./server/routes/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(express.static(path.join(__dirname + '/dist/meanshopcart')));
app.use('/api', api);
app.post('/sign-up', api.signup);
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/dist/meanshopcart/index.html'));
});
var port = process.env.PORT || '3000';
app.set('port', port);
var server = http.createServer(app);
//app.listen(port, function(){
// console.log("Server is running..!!");
//});
server.listen(port, function(err){
if(err){
return console.log('something bad happened', err);
}
console.log("Server is running..!!");
});
Routes Folder(routes/api.js)
my routes folder ./server/routes/api.js
var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/users');
const db = 'mongodb://localhost:27017/meanshopapp';
mongoose.connect(db, function(err){
console.log("mongo connection done");
if(err){
console.log("Error.."+err);
}
});
router.get('/', (req, res)=>{
console.log("get api ");
User.find({}, function(err, users) {
if (err) throw err;
// object of all the users
console.log(users);
});
res.send(users);
});
exports.signup = function(req, res, next){
console.log("new user entered");
var newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.password = req.body.password;
newUser.phoneNo = req.body.phone;
newUser.address = req.body.address;
newUser.save(function(err){
if(err){
console.log("error saving user");
}
else{
console.log("user inserted");
}
})
};
module.exports = router;
Model
this is my user schema user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name : { type: String },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
phoneNo: { type: Number },
address: { type: String }
});
module.exports = mongoose.model('user', userSchema, 'users');
You are using exports and module.exports.
Either you should follow #dimagolovin's answer
OR
module.exports = {router};
and use
`app.use('/api', api.router);
app.post('/sign-up', api.signup);`
Try to change the follwing in ./server/routes/api.js
function signup(req, res, next){
console.log("new user entered");
var newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.password = req.body.password;
newUser.phoneNo = req.body.phone;
newUser.address = req.body.address;
newUser.save(function(err){
if(err){
console.log("error saving user");
}
else{
console.log("user inserted");
}
})
};
module.exports = {router, signup};
It should do the work
var search = 1 + req.url.indexOf('?'); throws an error saying the statement to my left is undefined. Im using passportjs to create a login/registration page on my angular frontend. trying to make a post request to nodejs results in the above error. Im entirely new to the mean stack and ive tried several different tutorials to get myself up and running but have had some road blocks. can someone point in the right direction?
I've played around with just about every file moving around code and trying different solutions but nothing works, or one problem is solved but another occurs.
server.js
// set up ========================
var DATABASE = "mongodb://localhost:27017/smartHomeDevices";
var express = require("express");
var mongoose = require("mongoose"); //require monogDB Driver
var morgan = require("morgan"); // log requests to the console (express4)
var bodyParser = require("body-parser"); // pull information from HTML POST (express4)
var methodOverride = require("method-override"); // simulate DELETE and PUT (express4)
var passport = require("passport");
//var _ = require("lodash");
var http = require('http');
//setup
//app.models =
require("./Models/moduleIndex");
// Bring in the Passport config after model is defined
require('./config/passport');
//registering routes
var routes = require("./routes");
//Create App
var app = express();
app.use(passport.initialize());
//Add Middleware for REST API
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json);
app.use(bodyParser.json({
type: 'application/vnd.api+json'
}));
app.use(methodOverride("X-HTTP-Method-Override"));
app.use(morgan("dev"));
//CORS Support, makes API Public
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,");
res.header("Access-Control-Allow-Headers", "Content-Type,Authorization");
next();
});
app.use("/", routes);
// Connect to the db
mongoose.connect(DATABASE);
mongoose.connection.once("open", function() {
var serv = http.createServer(function(req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end();
console.log(routes(req.method, req.url));
}).listen(3000);
//module.exports = app;
console.log("Listening on 3000");
});
routes.js
//setup
var express = require('express');
var router = express.Router();
var jwt = require('express-jwt');
var auth = jwt({
secret: 'MY_SECRET',
userProperty: 'payload'
});
var ctrlProfile = require('./Controllers/ProfileController');
var ctrlAuth = require('./Controllers/RegisterUserController');
// profile
router.get('/profile', auth, ctrlProfile.profileRead);
// authentication
router.post('/register', ctrlAuth.register);
router.post('/login', ctrlAuth.login);
module.exports = router;
/*module.exports = {
"/smartDevices" : require("./Controllers/SmartDeviceController"),
"/registeredUsers": require("./Controllers/RegisterUserController")
};*/
resgisteredUsersControllers.js
//setup
//var Resource = require("resourcejs");
var restful = require("node-restful");
var passport = require('passport');
var mongoose = require('mongoose');
var User = mongoose.model('registeredUserModel');
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.register = function(req,res) {
console.log(req);
console.log("nw logging res");
console.log(res);
var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.username = req.body.username;
user.setPassword(req.body.password);
user.save(function(err) {
if(err)
console.log(err);
var token;
token = user.generateJwt();
res.status(200);
res.json({
"token" : token
});
});
next();
};
module.exports.login = function(req, res) {
passport.authenticate('local', function(err, user, info) {
var token;
// If Passport throws/catches an error
if (err) {
res.status(404).json(err);
return;
}
// If a user is found
if (user) {
token = user.generateJwt();
res.status(200);
res.json({
"token": token
});
} else {
// If user is not found
res.status(401).json(info);
}
})(req, res);
next();
};
/*module.exports = function(app, route) {
//setup controller for restful
// Resource(app,"",route,app.models.registeredUserModel).rest();
var rest = restful.model("registeredUserModel",
app.models.registeredUserModel
).methods(["get", "put", "post", "delete"]);
rest.register(app, route);
//return Middleware
return function(req, res, next) {
next();
};
};
*/
ProfileController.js
var mongoose = require('mongoose');
var User = mongoose.model('registeredUserModel');
module.exports.profileRead = function(req, res) {
// If no user ID exists in the JWT return a 401
if (!req.payload._id) {
res.status(401).json({
"message" : "UnauthorizedError: private profile"
});
} else {
// Otherwise continue
User
.findById(req.payload._id)
.exec(function(err, user) {
res.status(200).json(user);
});
}
};
Request object does not have url field.
I already looked at the other answers for similar questions, yet none of them worked for me. I two pieces of code, one to test that cookies were working(cookieTest.js), and one to actually use them(users.js). I tried moving the app.use() statements for the session middleware and the cookie middleware to no avail. Any ideas on how to fix this?
users.js
//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect("MY_DB");
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')
var User = require('../models/user.js');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var uuid = require('node-uuid');
var cookieParser = require('cookie-parser');
//Express Setup
var express = require('express');
var router = express.Router();
var app = express();
var expressValidator = require("express-validator");
var session = require('express-session');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: '_secret_', cookie: { maxAge: 60 * 60 * 1000 }, saveUninitialized: false, resave: false}))
//Routes
router.get('/register', function(req, res){
res.sendFile(appDir + "/views/register.html");
})
router.post('/register', function(req, res) {
req.check('name', 'Name must be Filled in').notEmpty();
req.check('email', 'Email must be Filled in').notEmpty();
req.check('email', "Invalid Email").isEmail();
req.check('password', 'Password Field must be Filled in').notEmpty();
req.check('password', 'Passwords do not Match').equals(req.body.password2)
var errors = req.validationErrors();
if(errors) res.send(errors)
else{
var newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
info: req.body.user_bio
});
User.createUser(newUser, function(err, user){
if(err) throw err;
});
res.redirect('../')
}
})
router.get('/login', function(req, res){
res.sendFile(appDir + "/views/login.html");
})
router.post('/login', function(req, res){
var email = req.body.email;
var candidatePass = req.body.password;
User.findOne({ 'email': email }, 'password id', function (err, user) {
if (err) return handleError(err);
User.checkPassword(candidatePass, user.password, function(err, isMatch){
if(err) throw err;
if(!isMatch) res.end('Password Incorrect!');
else{
req.session.userId = user.id;
res.redirect('../');
}
})
})
})
//Exports
module.exports = router;
When I run this I get the error TypeError: Cannot set property 'userId' of undefined, which means that req.session is undefined. However, when I run this, it works fine
var express = require('express');
var session = require('express-session');
var app = express();
var uuid = require('node-uuid');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Use the session middleware
app.use(session({
secret: 'jaredasch',
cookie: { maxAge: 60 * 60 * 1000 },
saveUninitialized: false,
resave: false
}))
// Access the session as req.session
app.get('/', function(req, res, next) {
var sess = req.session
if (sess.uuid) {
res.setHeader('Content-Type', 'text/html');
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.write('<form method = \'POST\'action = \'/\'><button type = \'submit\'></form>');
res.end()
} else {
sess.uuid = uuid.v4();
res.setHeader('Content-Type', 'text/html');
res.write('Set Up Session \n')
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.end('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
}
})
app.post('/', function(req,res){
req.session.destroy(function(err) {
if(err) throw err;
console.log('Session Destroyed')
})
res.redirect('/');
})
app.listen(3000, function(){
console.log('Listening on Port 3000')
});
Why does this work and the one above not, and how could I fix the one above? How would you reccomend fixing such an issue?
Try using app.use(cookieParser("_secret_")); so that its the same secret as with Express