I have made a database on pgAdmin 4 but values are not updated when sent through signup form on node.also npm install postgre-sql giving an error
var express = require('express');
var router = express.Router();
const { Pool,Client} = require('pg')
const connectionString='postgressql://postgres:12345##localhost:5432/postgres'
const client= new Client({
connectionString:connectionString
})
client.connect()
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/action',function(req,res){
var uname= req.query.username;
var pass= req.query.psw;
var em= req.query.email;
var DOB=req.query.dob;
var gen= req.query.gender;
client.query('INSERT INTO SIGNUP(username,email,password,DOB,gender) VALUES ("'+uname+'", "'+em+'", "'+pass+'","'+DOB+'","'+gen+'")',(err,res)=>{
console.log(err,res)
client.end()
} )
})
module.exports = router;
Looks like you might have a typo there
postgressql://postgres:12345##localhost:5432/postgres
should be postgresql://postgres:12345##localhost:5432/postgres
Related
I have this code in routes/apiRoutes.js that gets employees from the database but I need to include the table name with it.
const express = require("express");
const router = express.Router();
const db = require("../models");
//get all
router.get("/all", (req, res) => {
db.employee.findAll().then((employees) => res.send(employees));
});
//post new
router.post("/new", (req, res) => {
db.employee
.create({
text: req.body.text,
})
.then((submitedemployee) => res.send(submitedemployee));
});
module.exports = router;
I did try to use MYSQL syntax but it doesn't work
var seq = new Sequelize('mysql://localhost/mysql');
seq.query('show tables').then(function(rows) {
console.log(JSON.stringify(rows));
});
So i'm new to node.js and i've been working on a mini project, a student portal and i am stuck showing relevant courses only based on the students department and level.
student.js
var express = require('express');
var router = express.Router();
const {ensureAuthenticated} = require('../config/auth.js');
const {Student}= require('../models/schema.js');
var axios = require('axios');
var controller = require('../controller.js');
router.get('/register-courses',ensureAuthenticated,function(req, res, next) {
axios.get('http://localhost:3000/student/available-courses')
.then(
(response)=>{
console.log(response.data)
res.render('register-courses',{courses:response.data});
})
.catch(err=>{
console.log(err);
})
});
router.get('/available-courses', controller.getCourse);
module.exports = router;
ive narrowed down the problem to the req.user conditions which if i remove it renders all courses
controller.js
var {Course} = require ('./models/schema.js');
var {Student} = require ('./models/schema.js');
exports.getCourse = (req,res) =>{
const user = Student.findById(req.user._id); //problem is i cant access currently logged in user
console.log(user);
Course.find({departmentsOffering:user.department, level:user.level})
.then(items=>{
res.send(items)
})
.catch(
err=>{
console.log(err);
}
)
}
I think it's because you forgot to add the ensureAuthenticated middleware in your route declaration.
The declaration should be
router.get('/available-courses', ensureAuthenticated, controller.getCourse);
const mongoose = require('mongoose');
var express = require('express');
var bodyparser = require('body-parser');
var router = express.Router();
var db = mongoose.connection;
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.use(bodyparser.json());
router.use(bodyparser.urlencoded({extended:true}));
router.post('/singin/data',function(req,res){
console.log('post inside');
var fname = req.body.fname;
var lname = req.body.lname;
var email = req.body.email;
var password = req.body.password;
var data = {
'fname':fname,
'lname':lname,
'email':email,
'password':password
}
db.collection('signup').insertOne(data,function(err,info){
if(err) throw err;
console.log("Inserted",info);
});
console.log(email);
res.redirect('signin');
});
module.exports = router;
in get method i get data properly but in post method i can't post
data into database..
i create mongoose schema also in another models folder and also install mongoose also but major problem is on submit form button i get error can't post /signin
I think you need to use your model from mongoose (import) and depends on the version of DB you can try with de deprecate method save()
router.post('/singin/data',function(req,res){
console.log('post inside');
var fname = req.body.fname;
var lname = req.body.lname;
var email = req.body.email;
var password = req.body.password;
var data = new USERMODEL({
'fname':fname,
'lname':lname,
'email':email,
'password':password
})
db.collection('signup').save(data, (err, result) => {
if (err){
res.status(500).json({ status: 'something is wrong' })
//return next(err);
} else {
res.status(200).json({ status: 'ok' })
//return next();
}
})
I'm a beginner for NodeJS. For login functionality implement I needed to Set Up Passport to Handle the Express Authentication.
Here is my index.js
const express = require ('express');
const bodyParser = require ('body-parser');
const cors = require ('cors');
const path = require ('path');
//const passport = require ('passport');
const {mongoose} = require ('./db.js');
var employeeController = require('./controllers/employeeController.js');
var reservationController = require('./controllers/reservationController.js');
var app = express();
app.use(bodyParser.json());
app.use(cors({origin: 'http://localhost:4200'}));
app.listen(3000, () => console.log('server started at port :3000'));
app.use('/employees',employeeController);
app.use('/reservations',reservationController);
Here I commented out passport
This is my employee controller which retrieve data
const express = require ('express');
var router= express.Router();
var ObjectId = require('mongoose').Types.ObjectId;
var {Employee} = require('../models/employee');
// =>localhost:3000/employees
router.get('/',(req,res) => {
Employee.find((err,docs) => {
if(!err) {res.send(docs);}
else {console.log('error in retrieving employees :' + JSON.stringify(err,undefined,2)); }
});
});
router.get('/:id',(req,res)=>{
if(!ObjectId.isValid(req.params.id))
return res.status(400).send('No record with given id : ${req.params.id}');
Employee.findById(req.params.id,(err,doc) =>{
if(!err){res.send(doc);}
else{console.log('error in retriving employee:'+JSON.stringify(err,undefined,2));}
});
});
router.post('/',(req,res) =>{
console.log(req.body);
var emp = new Employee ({
name: req.body.name,
position: req.body.position,
office: req.body.office,
salary: req.body.salary,
});
emp.save((err,doc) => {
if(!err) {res.send(doc);}
else{console.log('error in saving employee'+ JSON.stringify(err,undefined,2));}
});
});
router.put('/:id', (req, res)=>{
if(!ObjectId.isValid(req.params.id))
return res.status(400).send('No record with given id : ${req.params.id}');
var emp = {
name: req.body.name,
position: req.body.position,
office: req.body.office,
salary: req.body.salary,
};
Employee.findByIdAndUpdate(req.params.id,{$set:emp},{new:true},(err,doc) =>{
if(!err){res.send(doc);}
else{console.log('error in updating employee:'+JSON.stringify(err,undefined,2));}
});
});
router.delete('/:id',(req,res)=>{
if(!ObjectId.isValid(req.params.id))
return res.status(400).send('No record with given id : ${req.params.id}');
Employee.findByIdAndRemove(req.params.id,(err,doc) =>{
if(!err){res.send(doc);}
else{console.log('error in deleting employee:'+JSON.stringify(err,undefined,2));}
});
});
module.exports = router;
My app is retrieving data from the mongodb perfectly. But when I remove the comment out of the passport in the index.js data retrieval not happen. I can't figure out what's went wrong when I add passport.
Please help me as I'm new one for NodeJS.
passport is not a middleware.
const path = require ('path');
const passport = require ('passport');
....
app.use(passport.initialize())
.... //your routes
Hope this solves your issue
Trying to make a login app with nodejs express.
However after I run it. it shows TypeError: express.Router is not a function.
My express is the latest version4.13.4. Can anyone help me?Here is the code.
var User = require('../modules/user');
var config = require('../../config');
var secretKey = config.secretKey;
module.exports = function(app,express){
var api = express.Router;
api.post('/signup', function(req,res){
var user = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password
});
user.save(function(err){
if(err){
res.send(err);
return;
}
res.json({ message: 'user has been created'});
})
});
return api;
};
It should be var api = express.Router();
I can't see the require to include the express library.
var express = require('express');
var app = express();
Also remember to make
$ npm install express --save
To install it.
Here is the reference
http://expressjs.com/en/4x/api.html
http://expressjs.com/en/starter/installing.html
var api = express.Router();
or try this code :
var router = require('express').Router(),
User = require('../modules/user'),
config = require('../../config');
router
.post('/signup', function (req, res, next) {
var user = new User(req.body);
user.save(function (err) {
if (err) res.send(err);
else res.json({message: 'user has been created'});
})
});
module.exports = router;
You need to require the express module, before calling the Router method, with this you can add more HTTP method to "/signup" route.
var express = require('express');
var User = require('../modules/user');
var config = require('../../config');
var api = express.Router();
var secretKey = config.secretKey;
module.exports = function(api) {
api.route('/signup')
.post(function(req, res) {
var user = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password
});
user.save(function(err) {
if (err) res.send(err);
res.json({ message: 'user has been created'});
});
});
};
Try adding require('http') or require('https') as the first require statement.
I had the problem of var express = express() returning the error: not a function. After some spelunking in the express directories, I saw that the sample code required http or https first. So, add one (perhaps both) as first (and or second) file imports.
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
router.get('/', (req, res)=>{
res.send('Course Controller');
});
module.exports = router;
write npm i express -s
I've tried and it's working for me