I have some code to create an account and have a login page and say true or false if you entered the correct details but instead it says 'Cannot post /membership/login/submit'.
my main.js code (the html files are basic and the forms are just standard tags with an action and a method, tell me if you want these)
var app = require('express')();
var http = require('http').Server(app);
var httpuse = require('http');
var io = require('socket.io')(http);
var MongoClient = require('mongodb').MongoClient;
var users = require(__dirname + '/local_js/users.js');
var public = __dirname + "/www/";
var bodyParser = require('body-parser')
var url = "mongodb://localhost:27017/";
const bcrypt = require('bcrypt');
var needle = require('needle');
const saltRounds = 10;
app.use(bodyParser.urlencoded({ extended: false }));
function rand(n) {
Math.floor(Math.random() * (n+1));
}
function getToken(hashedpass, user) {
return hashedpass+"_._"+user;
}
app.get('/', function(req, res){
res.sendFile(public + 'index.html');
});
app.get('/membership/create/form', function(req, res){
res.sendFile(public + 'user/create.html');
});
app.post('/membership/create/submit', function(req, res){
MongoClient.connect(url, function(errdd, db) {
if (errdd) throw errdd;
var dbo = db.db("boaichat");
bcrypt.hash(req.body.password, saltRounds, function(err, hash) {
if (err) {throw err;}
var newUser = { nickname: req.body.nickname, password: hash };
dbo.collection("users").insertOne(newUser, function(errd, ress) {
if (errd) throw errd;
console.log("1 user document inserted");
db.close();
res.send("200 OK");
});
});
});
});
app.get('/membership/login/form', function(req, res) {
res.sendFile(public + 'user/login.html');
});
app.post('membership/login/submit', function(req, res) {
MongoClient.connect(url, function(errdd, db) {
if (errdd) throw errdd;
var dbo = db.db("boaichat");
dbo.collection("users").findOne({nickname: req.body.nickname}, function(err, result) {
if (err) throw err;
if (result) {
bcrypt.compare(req.body.password, result.password, function(err, ress) {
console.log(ress);
res.send(ress);
});
}
});
db.close();
});
});
// IGNORE THIS
app.post('api/v1/getSessionValid', function(req, res) {
let token = req.body.token;
let userInfo = token.split('_._');
if (userInfo[0] && userInfo[1]) {
}
});
io.on('connection', function(socket){
console.log('connection');
socket.on('disconnect', function(){
console.log("disconnection");
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
it says 'Cannot post /membership/login/submit'.
Don't forget the / at the beginning of your route.
// Try this
app.post('/membership/login/submit', ...)
// Instead of
app.post('membership/login/submit', ...)
Related
i have been struggling for the pas few days i want to redirect to another page from my node.js server.
first by website is redirecting me to my server to do a task but when that task is done i want the server to redirect me back to my website.
here is the node js server code.
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongourl = "mongodb://localhost:27017/";
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
var urlQuery = url.parse(req.url, true).query;
removeItem(urlQuery.itemToRemove);
addItem(urlQuery.itemToAdd);
**// i have been trying to redirect to my html site **
**// i have got a error saying TypeError: res.redirect is not a function**
res.redirect('index.html');
res.end();
}).listen(8080);
function removeItem(remove) {
if (remove !== undefined) {
MongoClient.connect(mongourl, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = {
itemName: remove
};
dbo.collection("shoppingCart").deleteOne(myquery, function (err, obj) {
if (err) throw err;
console.log("deleted:" + myquery);
db.close();
});
});
}
}
function addItem(create) {
if (create !== undefined) {
MongoClient.connect(mongourl, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = {
itemName: create
};
dbo.collection("shoppingCart").insertOne(myobj, function (err, res) {
if (err) throw err;
console.log("document inserted:" + myobj);
db.close();
});
});
}
}
You are getting that error because response.redirect() is an express function and your app is based purely on nodejs http library.
You can accomplish what you have mentioned this way:
res.writeHead(301,{Location: 'your-location'});
res.end();
You are not creating the server properly. Try to keep your code clean,Write separate API for serving index.html, not inside creating the server.
TypeError: res.redirect is not a function
This is because res.redirect is an express function and you're using plain http node server.
You can consider using express for handling redirects for you.
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongourl = 'mongodb://localhost:27017/';
// express
const express = require('express');
const app = express();
const port = 8080;
// for templating
// create `views/` folder
// and place `index.pug` and `redirected-page.pug`
app.set('view engine', 'pug');
app.get('/redirect', (req, res) => {
res.render('redirected-page');
});
app.get('/', (req, res) => {
var urlQuery = url.parse(req.url, true).query;
Promise.all([
removeItem(urlQuery.itemToRemove),
addItem(urlQuery.itemToAdd),
]).then(() => {
res.redirect('redirect');
});
});
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
function removeItem(remove) {
if (remove !== undefined) {
MongoClient.connect(mongourl, function(err, db) {
if (err) throw err;
var dbo = db.db('mydb');
var myquery = {
itemName: remove,
};
dbo.collection('shoppingCart').deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log('deleted:' + myquery);
db.close();
});
});
}
}
function addItem(create) {
if (create !== undefined) {
MongoClient.connect(mongourl, function(err, db) {
if (err) throw err;
var dbo = db.db('mydb');
var myobj = {
itemName: create,
};
dbo.collection('shoppingCart').insertOne(myobj, function(err, res) {
if (err) throw err;
console.log('document inserted:' + myobj);
db.close();
});
});
}
}
app.listen(port, () => console.log(`Server is running at ${port}!`));
TypeError: Cannot read property 'then' of undefined
Can you help me fix this? Thank you.
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017',
function(err, db) {
if(err){
throw err;
}else{
console.log("connected");
}
})
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));
app.post('/post-feedback', function (req, res) {
dbConn.then(function(db) {
delete req.body._id; // for safety reasons
db.collection('feedbacks').insertOne(req.body);
});
res.send('Data received:\n' + JSON.stringify(req.body));
});
app.get('/view-feedbacks', function(req, res) {
dbConn.then(function(db) {
db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
res.status(200).json(feedbacks);
});
});
});
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
TypeError: Cannot read property 'then' of undefined
Can you help me fix this? Thank you.
The following approach should get you started but should not use this for production (Reference: How do I manage MongoDB connections in a Node.js web application?). Read through for another production starters.
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var dbConn = function() {
return new Promise((resolve, reject) => {
mongodb.MongoClient.connect('mongodb://localhost:27017',
function(err, db) {
if(err){
return reject(err);
}else{
return resolve(db);
}
});
});
}
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));
app.post('/post-feedback', function (req, res) {
dbConn()
.then(function(db) {
delete req.body._id; // for safety reasons
db.collection('feedbacks').insertOne(req.body);
res.send('Data received:\n' + JSON.stringify(req.body));
})
.catch(err => {
console.log(err)
res.send('Error');
})
});
app.get('/view-feedbacks', function(req, res) {
dbConn()
.then(function(db) {
db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
res.status(200).json(feedbacks);
});
})
.catch(err => {
console.log(err);
res.status(500).json({});
});
});
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
Production Starter:
Ideally you will have something like following say in a file db.js
let mongoClient = require('mongodb').MongoClient,
logger = require('winston');
function DATABASE() {
this.dbObj = null;
this.myCollection = null; // You will need to add more collections here
}
DATABASE.prototype.init = function (config, options) {
let self = this;
self.config = config; //can pass a config for different things like port, ip etc.
self.logger = logger;
return new Promise(function (resolve, reject) {
if (self.initialized) {
return resolve(self);
}
let connectionUri = "mongodb://localhost:27017"; //self.config.mongo.connectionUri;
mongoClient.connect(connectionUri, {native_parser: true}, function (err, db) {
if (err) {
reject(err);
}
else {
self.dbObj = db;
self.myCollection = db.collection('myCollection');
self.initialized = true;
self.logger.info("db init success");
return resolve(self);
}
});
});
};
var dbObj = null;
var getdbObj = function () {
if (!dbObj) {
dbObj = new DATABASE();
}
return dbObj;
}();
module.exports = getdbObj;
In your main app start file you will have something like:
let dbObj = require('./db.js');
dbObj.init()
.then(db => {
console.log('db initialized successfully');
//db.dbObj.collection('myCollection').find()
//or
//db.myCollection.find() because this has been already initialized in db.js
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));
app.post('/post-feedback', function (req, res) {
delete req.body._id; // for safety reasons
db.dbObj.collection('feedbacks').insertOne(req.body);
res.send('Data received:\n' + JSON.stringify(req.body));
});
app.get('/view-feedbacks', function(req, res) {
//db.collection('feedbacks')
});
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' )
})
.catch(err => console.log(err));
Try this, dbConn is not promise
app.post('/post-feedback', function (req, res) {
mongoose.connection.db.collection('feedbacks', function (err, collection) {
collection.insertOne(req.body);
res.send('Data received:\n' + JSON.stringify(req.body));
});
// OR
const Model = mongoose.model('feedbacks');
let model = new Model();
model = Object.assign(model, req.body);
model.save().then((result) => {
res.send('Data received:\n' + JSON.stringify(req.body));
});
});
Its working .
If you are getting any TypeError (UnhandledPromiseRejectionWarning: TypeError: db.collection is not a function) form mongodb. Just change the version of mongodb to -
"mongodb": "^2.2.33"
"use strict"
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/feedback';
// no need to call then() yet
var dbConn = MongoClient.connect(url);
app.set('port', 5000);
app.listen(app.get('port'), function() {
console.log('feedback is running on port', app.get('port'));
});
app.get('/view-feedback', function(req, res, next) {
// the connection is opened
dbConn.then(function(db) {
// var dbo = db.db("feedback");
db.collection('feedback').find({}).toArray().then(function(docs) {
// return docs;
res.json(docs)
});
});
});
I have a Express server resolving GET /companies/:id/populate/. Now, I would like to setup GET /companies/populate/ (without the :id). However, I can't make this route to work. If I try, for example, GET /companies/all/populate/, it works, so it seems the pattern for an Express route is path/:key/path/:key.
Is this true? Thanks!
Edit: Adding code.
server.js
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoUri = 'mongodb://localhost:27017';
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function() {
throw new Error('Unable to connect to database at' + mongoUri);
});
// runs Express
var app = express();
// uses Cors
app.use(cors());
// uses bodyParser
app.use(bodyParser.json());
// requires Mongo models
require('./models');
// includes routes.js, passing the object 'app'
require('./routes')(app);
// listens for connections on port 3000
app.listen(3000, function() {
console.log("Express started on Port 3000");
});
routes.js
module.exports = function(app) {
// thumbs up if everything is working
app.get('/', function(req, res, next) {
res.send('👍');
console.log('Server Running');
res.end();
});
// companies
var companies = require('./controllers/companies');
app.get('/companies', companies.findAll);
app.get('/companies/:id', companies.findById);
app.get('/companies/:id/populate', companies.populate);
app.get('/companies/populate', companies.populateAll);
app.post('/companies', companies.add);
app.patch('/companies/:id', companies.patch);
app.delete('/companies/:id', companies.delete);
};
/controllers/companies.js
var mongoose = require('mongoose');
Company = mongoose.model('Company');
// GET /companies
// status: works, needs error handling
exports.findAll = function(req, res) {
Company.find({}, function(err, results) {
return res.send(results);
});
};
// GET /companies/:id
// status: works, needs to check error handling
exports.findById = function(req, res) {
var id = req.params.id;
Company.findById(id, function(err, results) {
if (results) res.send(results);
else res.send(204);
});
};
// POST /companies
// status: works, needs error handling
exports.add = function(req, res) {
Company.create(req.body, function(err, results) {
if (err) {
return console.log(err)
} else {
console.log('company created');
}
return res.send(results);
});
};
// PATCH /companies/:id
// status: works, needs error handling
exports.patch = function(req, res) {
var id = req.params.id;
var data = req.body;
Company.update( { '_id' : id }, data, function(err, numAffected) {
if (err) return console.log(err);
return res.send(200);
});
};
// DELETE /companies/:id
// status: works, needs error handling, make sure that we are sending a 204 error on delete
exports.delete = function(req, res) {
var id = req.params.id;
Company.remove({ '_id': id }, function(results) {
console.log('deleted ' + id); // tester
return res.send(results);
});
};
// GET /companies/:id/populate
exports.populate = function(req, res) {
var id = req.params.id;
Company
.findOne({ _id: id })
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
// GET /companies/populate
exports.populateAll = function(req, res) {
Company
.find({})
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
I am trying to get response data from model(database) to controller
here is model
var database = require('../config/db');
exports.getAllBatch = function(done) {
database.query('SELECT batchName from batch', function (err, rows) {
if (err) return console.log(err);
else {
console.log(null, rows);
return rows;
}
})
};
here is controller
code to access data from model.
var express = require('express');
var router = express.Router();
var batch=require('../models/BatchModel');
var myParser = require("body-parser");
var app = express();
router.get('/getbatch', function(req, res, next)
{
var resp=batch.getAllBatch();
res.send(resp);
//not displaying anything on browser
});
});
How I get response on browser please guide me.Thank you in advance.
That is good code, the only thing missing is setting the body parser you have required
app.use(myParser.json())
Your functions are using a callback pattern, but you're not calling or checking the callbacks.
Model
var database = require('../config/db');
exports.getAllBatch = function(done) {
database.query('SELECT batchName from batch', function (err, rows) {
if (err) {
console.log('Err', err);
return done(err);
}
else {
console.log('Rows', rows);
return done(null, rows);
}
});
};
Controller
var express = require('express');
var router = express.Router();
var batch=require('../models/BatchModel');
var myParser = require("body-parser");
var app = express();
router.get('/getbatch', function(req, res, next) {
batch.getAllBatch(function(err, rows) {
if (err) {
res.status(500).send(err);
} else {
res.send(rows);
}
});
});
I need an API to insert data from android to mongodb , I follow this ,the code can run , have NO error , and I use POSTMAN try to post some data , it always say could not get any respone , seem to have an error connecting to 192.168.1.105:3000/songs
but I can use find all api and findByID.
This took me hours , please help , so depress :(
app.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
songs = require('./routes/route');
var jsonParser = bodyParser.json();
app.post('/songs', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.findAll);
app.get('/findById/:id',songs.findById);
app.get('/songs',songs.addSong);
route
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://XXXX:XXXX#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving song: ' + id);
db.collection('songs', function(err, collection)
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.addSong = function(req, res) {
var song = req.query;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
{console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
Okay so I changed a few things in your code. I'm successfully getting the request body in the app.js file. Do have a look at the code.
route.js
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://localhost:27017/test";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.addSong = function(req, res) {
var song = req.body;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
Notice that I have changed the URI to localhost, so change it again to the one you specified.
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
songs = require('./routes/route');
app.post('/songs', function(req, res) {
console.log("Request.Body : " + JSON.stringify(req.body));
if (!req.body) return res.sendStatus(400);
songs.addSong(req, res);
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.addSong);
Since your only problem was that you weren't able to get the request body. You'll be able to get it with this code.
Also since your app.get('/songs',songs.addSong); is of type GET, you'll not be able to send POST Data through it. So change it to
app.post('/songs',songs.addSong);
Hope this helps.