Cannot GET /api/addmasterlist on app.post - node.js

server.js
var express = require('express');
var mysql = require('mysql');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require("method-override");
var request = require("request");
app.use(express.static(__dirname + '/public'));
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({'extended' : 'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json'}));
app.use(methodOverride());
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
port : 3306,
user : 'root',
password : 'xxxxxxx',
database : 'masterlist',
debug : false
});
//Rest APIs
app.get('/api/fetchmasterlist', function(req, res){
pool.getConnection(function(err, connection){
if(!err){
//Query
var strquery = "SELECT * FROM students";
connection.query(strquery, function(err, rows){
if(err){
res.json("Error in Query." + err);
}else{
res.json(rows);
}
});
}else {
//Return an Error
connection.release();
connection.destroy();
res.json("Error geting connection from DATABASE.");
return;
}
});
});
app.post('/api/addmasterlist', function(req, res){
pool.getConnection(function(err, connection){
if(!err){
//Query
/*var post = req.body.param;*/
var strquery = "INSERT INTO students(id, studentid, studentname, course, year) VALUES (?, ?, ?, ?, ?)";
connection.query(strquery, [req.body.id, req.body.studentid, req.body.studentname, req.body.course, req.body.year], function(err, rows){
if(err){
res.json("Error in Query." + err);
}else{
res.json("Success in inserting the new student." + rows);
}
});
}else {
//Return an Error
/*connection.release();
connection.destroy();*/
res.json("Error geting connection from DATABASE.");
return;
}
});
});
// application route
app.get('*', function(req, res){
res.sendfile('./public/index.html') // load the single static file
});
// listen
app.listen(8080);
console.log("App listening on port 8080");
my api/addmasterlist is not working and it gives me
Cannot GET /api/addmasterlist
error on the browser
using app.get on the masterlist seems to work fine and reflect on the database the problem is it will not work on my angular.js
okay using app.get seems to work but can anyone help me is this the proper way of pushing through nodejs? using angular
$scope.saveNewStudent = function(){
var dataa = $scope.studentmasterlist.push({
id: ($scope.studentmasterlist.length + 1),
studentid: $scope.studentid,
studentname: $scope.studentname,
course: $scope.course,
year: $scope.year,
});
$http.get('/api/addmasterlist', dataa).success(function(data, status) {
console.log('Data posted successfully');
})
//Clear the scope
$scope.studentid = "";
$scope.studentname = "";
$scope.course = "";
$scope.year = "";
}

The problem is that you declared your /api/addmasterlist endpoint as a POST request. Try changing it to GET and it might work as you expected.
Change this:
app.post('/api/addmasterlist', function(req, res){
To this:
app.get('/api/addmasterlist', function(req, res){
Alternatively, you can change your angular's http from get to post:
Change:
$http.get('/api/addmasterlist', dataa).success(function(data, status) {
to
$http.post('/api/addmasterlist', dataa).success(function(data, status) {

Related

Cors proxy issues within server.js file(react, express,sql)

I have made a basic fullstack website using mssql and express. Originally the get routes worked but after implementing the post route they have stopped.
I believe I am receiving a cors error which is.
Proxy error: Could not proxy request /admin-view-users from localhost:3000 to http://localhost:5000/.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
my server.js
const express = require("express");
const sql = require("mssql");
var cors = require("cors");
const path = require("path");
var bodyParser = require("body-parser");
const port = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
const config = {
user: "sas",
password: "Mypassword456",
server: "DEVSQL_2014", // You can use 'localhost\\instance' to connect to named instance
database: "TestDBWebsite"
};
//AdminView users just pulls the users from the database
app.get("/admin-view-users", cors(), function(req, res) {
// connect to your database
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * from Users2 ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
res.end();
});
});
});
app.get("/admin-view-users", function(req, res) {
// connect to your database
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * from Users2 ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
res.end();
});
});
});
app.get("/user-questions", function(req, res) {
// connect to your database
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * from Questions ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
});
});
});
//
var jsonParser = bodyParser.json();
app.use(express.bodyParser());
app.post("/admin-Add-Users", jsonParser, function(request, response) {
var email = req.body.email;
var password = req.body.password;
var request = new sql.Request();
// query to the database and get the records
console.log(email, password); // your JSON
// echo the result back
console.log(request.body);
request.query(
"insert into Login (email, password) values ('" +
email +
"','" +
password +
"')",
function(err, recordset) {
if (err) console.log(err);
}
);
response.send({ message: "Success" });
});
app.listen(port, () => `Server running on port ${port}`);
I have included "app.use(cors());" which I assumed woudl resolve this but it has not.
Please advice if you can .
The first thing that comes up to my mind is the double use of CORS.
You are putting it uptop in the middleware stack and then calling it again in here:
app.get("/admin-view-users", cors(), function(req, res) {
Please try using this only once:
https://www.npmjs.com/package/cors

GET /signup - - ms - -(both get and post not working, it was a while idk whats wrong)

1.GET /signup - - ms - -(both GET and POST not working, it was a while I don’t know whats wrong)
2. please check below code
3.server.js. This this the app code that you have requested.Kindly go through it. Also the value for link is replaced by word link as it is private.
4. There are two files in this. Server.js and user.js kindly check it out.
var router = require("express").Router();
var User = require("../models/user.js");
router.get("/signup", function(req, res){
res.send("hello");
});
router.post('/signup', function(req, res, next){
var user = new User();
user.profile.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
User.findOne( { email : req.body.email }, function(err, existingUser) {
if(existingUser){
console.log(req.body.email + "already exists");
return res.redirect("/signup");
}
else{
user.save(function(err, user){
if(err) return next(err);
res.send("New user has been added");
});
}
});
});
module.exports = router;
//server.js code
var express = require("express");
var morgan = require("morgan");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var User = require("./models/user.js");
var ejs = require("ejs");
var engine = require("ejs-mate");
var app = express();
mongoose.connect('link', function(err){
if(err){
console.log(err);
}
else{
console.log("connected to database");
}
});
//middle ware
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.engine("ejs", engine);
app.set("view engine", "ejs");
var mainRoutes = require("./routes/main.js");
var userRoutes = require("./routes/user.js");
app.use(mainRoutes,function(err){
if(err){
console.log("error is here")
}
});
app.use(userRoutes, function(err){
if(err){
console.log("error is here in 2" );
}
});
//listen to port 3000
app.listen(3000, function(err){
if(err) throw err;
console.log("Server has started");
});
removed the call back function from app.use() and it worked.

Multiple Sessions in node.js

I am making my first app in node.js,express.js,express-session.js and angular.js.
I have made a simple login feature in it. A user logs in and can see all his online friends.
The problem that i am facing is that i open one window in chrome and the other in firefox. login from different accounts but friends are shown(in both browser windows) who has the latest login. How to handle this problem?
Here is my server.js file
var app = require("express")();
var session = require('express-session');
var mysql = require("mysql");
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require("socket.io")(http);
//initialize the session
app.use(session({
secret: "online",
resave: true,
saveUninitialized: true
}));
var session_data;
app.use(require("express").static('data'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
/* Creating MySQL connection.*/
var con = mysql.createPool({
connectionLimit : 100,
host : 'localhost',
user : 'root',
password : '',
database : 'testDbChat'
});
app.get("/",function(req,res){
res.sendFile(__dirname + '/data/messages.html');
});
/* Socket connectes ur machine to server */
io.on('connection',function(socket){
socket.on('update_list',function(data){
//data.purpose;
console.log(data);
if((String(data.purpose.trim()))=='list friends'){
var query="update members set online = ? where id = ?";
con.query(String(query),['Y',data.id],function(err,rows){
// var query="select * from user where id !='"+data.id+"'";
var query="SELECT members.FirstName,members.LasName,members.ID,friends.FriendsTwoID,friends.FriendOneID FROM friends JOIN members ON members.ID = friends.FriendsTwoID OR members.ID = friends.FriendOneID WHERE (friends.FriendOneID = '"+data.id+"' OR friends.FriendsTwoID = '"+data.id+"') AND (friends.`Status` = 'Confirmed' AND members.ID != '"+data.id+"')";
con.query(String(query),function(err,rows){
io.emit('logout update',JSON.stringify(rows));
});
});
}
else{
var query="update members set online = ? where id = ?";
con.query(String(query),['N',data.id],function(err,rows){
//var query="select * from user where id !='"+data.id+"'";
var query="SELECT members.FirstName,friends.FriendsTwoID From friends JOIN members ON members.ID = friends.FriendsTwoID where friends.FriendOneID ='"+data.id+"' AND friends.Status = 'Confirmed' ";
con.query(String(query),function(err,rows){
io.emit('logout update',JSON.stringify(rows));
});
});
}
});
});
app.post('/get_list', function (req, res) {
var query="select * from friends";
con.query(String(query),function(err,rows){
res.write(JSON.stringify(rows));
res.end();
});
});
app.post('/login', function (req, res) {
session_data=req.session;
console.log(req.session); // depricated
data = {
name:req.body.name,
password:req.body.password
};
console.log(data);
session_data.password=data.password;
session_data.name=data.name;
var obj={};
var query="select * from members where Username = '"+data.name+"' and Password='"+data.password+"'";
con.query(String(query),function(err,rows){
if(rows.length > 0){
console.log(rows[0].ID);
var un=new Buffer(String(rows[0].FirstName)).toString('base64');
var ui=new Buffer(String(rows[0].ID)).toString('base64');
obj.path_name="/messages.html#?un="+un+"&ui="+ui;
res.write(JSON.stringify(obj));
res.end();
}else{
obj.path_name="invalid";
res.write(JSON.stringify(obj)); // writes the response but has to be sent by response.end
res.end();
}
});
});
app.get('/messages', function (req, res) {
session_data=req.session;
if(session_data.name){
res.sendFile(__dirname + '/data/messages.html');
}else{
res.redirect('/');
}
});
app.post('/logout', function (req, res) {
var query="update members set online = ? where id = ?";
con.query(String(query),['N',req.body.id],function(err,rows){});
req.session.destroy(function(err){
res.end();
});
});
app.get('/home', function (req, res) {
session_data=req.session;
console.log(session_data);
if(session_data.name){
res.sendFile(__dirname + '/data/messages.html');
}else{
res.redirect('/');
}
});
http.listen(3000,function(){
console.log("Listening on 3000");
});

Dynamic CRUD functions with Node, Express and Pug

Hi I am new to backend node applications and I am trying to create a clean API driven node.js app without frameworks by working with scripts and pug template engine.
I have created a serve.js file with all the necessary code:
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
const bodyParser = require("body-parser");
var mongodb = require("mongodb");
const MongoClient = require('mongodb').MongoClient
var ObjectID = mongodb.ObjectID;
var indexRoutes = require('./routes/index');
var thePort = process.env.PORT || 5000;
var SECTIONS_COLLECTION = "sections";
//make results available as json
app.use(bodyParser.json());
//External database identifier
var db;
//Path to the database with URI
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2orjhen7knanjpfmd7#ds014586.mlab.com:19986/heroku_fmvc5nhk';
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(dbpath, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
//static folder directory
app.use(express.static(__dirname + '/dist'));
// Initialize the app.
var server = app.listen(process.env.PORT || thePort, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
//set up routes directory
app.use('/', indexRoutes);
// Views and Template Engine
//app.set('views', __dirname + './views');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// sections API ROUTES:
/* "/api/sections"
* GET: finds all sections
* POST: creates a new contact
*/
app.get("/api/sections", function(req, res) {
db.collection(SECTIONS_COLLECTION).find({}).toArray(function(err, docs) {
if (err) {
handleError(res, err.message, "Failed to get sections.");
} else {
res.status(200).json(docs);
}
});
});
app.post("/api/sections", function(req, res) {
var newContact = req.body;
if (!req.body.name) {
handleError(res, "Invalid user input", "Must provide a name.", 400);
}
db.collection(sections_COLLECTION).insertOne(newContact, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new contact.");
} else {
res.status(201).json(doc.ops[0]);
}
});
});
/* "/api/sections/:id"
* GET: find contact by id
* PUT: update contact by id
* DELETE: deletes contact by id
*/
app.get("/api/sections/:id", function(req, res) {
db.collection(SECTIONS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get contact");
} else {
res.status(200).json(doc);
}
});
});
app.put("/api/sections/:id", function(req, res) {
var updateDoc = req.body;
delete updateDoc._id;
db.collection(SECTIONS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to update contact");
} else {
updateDoc._id = req.params.id;
res.status(200).json(updateDoc);
}
});
});
app.delete("/api/sections/:id", function(req, res) {
db.collection(SECTIONS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
if (err) {
handleError(res, err.message, "Failed to delete contact");
} else {
res.status(200).json(req.params.id);
}
});
});
In my views\about.pug template I reference my JSON object's contents.
//--about.pug
extends index.pug
block div.root
h2= #{about.heading}
h3= #{about.summary}
p #{about.content}
In my routesroutes/index.js I have pre-existing "flat" examples with pug then one dynamic about example:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render(
'index',
{
title: 'Welcome to Awesome Place',
header: 'Home',
summary: 'This is my home. It can\'t be any simpler'
}
)
})
Dynamic example:
//About
router.get('/about', function (req, res) {
//retrieve all home from Mongo
db.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) {
if (err) {
handleError(res, err.message, "Failed to get sections.");
} else {
res.render('about', {})
console.log(result)
}
}
})
The above is returning a db is not defined error.
If var indexRoutes = require('./routes/index'); is required as part of my server.js file, why can't it find the value of db?
UPDATED CODE (TOO MANY ERRORS)
//server.js
//APP Dependences
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var indexRoutes = require('./routes/index');
var bodyParser = require("body-parser");
//PORT
var thePort = process.env.PORT || 5000;
// Views and Template Engine
//app.set('views', __dirname + './views');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//Documents
app.use(bodyParser.json());
//static folder directory
app.use(express.static(__dirname + '/dist'));
//set up routes directory
app.use('/', indexRoutes);
// Catch errors
app.use(function(req, res, next) {
res.status(404).sendFile(process.cwd() + '/app/views/404.htm');
});
// Initialize the app.
var server = app.listen(process.env.PORT || thePort, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
var mongodb = require("mongodb");
const MongoClient = require('mongodb').MongoClient
var ObjectID = mongodb.ObjectID;
var SECTIONS_COLLECTION = "sections";
//External database identifier
var db;
//Path to the database with URI
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2ovanbfd7knanjpfmd7#ds019986.mlab.com:19986/heroku_fmvc5nhk';
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(dbpath, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || thePort, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
//db.js
var express = require('express');
var mongodb = require("mongodb");
var MongoClient = require('mongodb').MongoClient
var ObjectID = mongodb.ObjectID;
var assert = require('assert');
//Path to the database with
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2ovahen7knanjpfmd7#ds019986.mlab.com:19986/heroku_fmvc5nhk';
//Get the section
var SECTIONS_COLLECTION = "sections";
// Use connect method to connect to the server
var database;
function connectMongo(cb){
MongoClient.connect(dbpath , function(err, database) {
assert.equal(null, err);
console.log("Connected successfully to server");
cb(database);
});
}
module.exports = connectMongo;
//routes/index.js
var express = require('express');
var router = express.Router();
var connectDB = require ('../db')
router.get('/', function (req, res) {
res.render(
'index',
{
title: 'Welcome to Awesome Place',
header: 'Home',
summary: 'This is my home. It can\'t be any simpler'
}
)
})
connectMongo(function(database){
//About
router.get('/about', function (req, res) {
//retrieve all home from Mongo
database.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) {
if (err) {
handleError(res, err.message, "Failed to get sections.");
} else {
res.render('about', {})
console.log(result)
}
}
})
}
router.get('/work', function (req, res) {
res.render(
'work',
{
title: 'Work, Work, Work , Work...',
header: 'Work life',
summary: 'My first work for this bitch',
imgUrl: '/img/firaz.jpg'
}
)
})
router.get('/contact', function (req, res) {
res.render(
'contact',
{
title: 'Contact Me Any Time',
header: 'Contact Me Any Time',
summary: 'Fill the form below to be contacted'
}
)
})
module.exports = router;
Because db variable is not global by requiring var indexRoutes = require('./routes/index'); you are importing the objects from routes/index file to server not the other way around.
what you can do is make your db variable global global.db and access it anywhere or create a seperate file for mongo db connection and require that in routes file
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/database';
// Use connect method to connect to the server
var database;
function connectMongo(cb){
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
cb(db);
});
}
module.exports = connectMongo;
This github Repo got good structure for mongoDB
https://github.com/OmarElGabry/chat.io

How to use mongoose or mongodb to check for repeated data (Node.js + Express)

I was wondering if there was a way to check for repeated values before entering them into the database using mongodb and mongoose. I am basically looking for a way to validate the data in a sense that the data is not repeated so I don't waste space. I was hoping someone could point me in the right direction or show me a a solution, thank you.
App.js:
var print = require('./print');
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var config = require('./config.js');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render("post");
print("All is in order");
})
app.listen(config.port, function() {
print(`listening on ${config.port}`);
})
MongoClient.connect(config.localUrl, function(err, db) {
if(err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collection = db.collection('users');
app.post('/post', function(req, res) {
var name = req.body.name
var email = req.body.email
res.send(`You sent the name ${name} and the email ${email}`);
var user1 = {};
user1.name = name;
user1.email = email;
//validate no repeated values
collection.insert(user1, function(err,result){
if (err) {
console.log(err);
} else {
console.log('The Results', result);
db.close();
}
})
})
})
You Can use $setOnInsert
https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/#op._S_setOnInsert with upsert:true.

Resources