I try to understand the code of a friend and I connect to js and nodejs for the first time,I want to know the meaning of "/" , req res next.
here is the code
in routes/task.js
var express = require('express');
var router = express.Router();
var Task = require('../models/task');
router.post("/", function(req, res, next){
var task = req.body;
Task.create(task, function(err, task){
if (err) {
return res.status(400).send("err in post /task");
} else {
return res.status(200).json(task);
}
});
});
router.get("/", function(req, res, next){
Task.find({}, function(err, tasks){
if(err){
return res.status(400).send("err in get /task");
}else{
console.log(tasks);
return res.status(200).json(tasks);
}
})
});
module.exports = router;
Task is a data module exports in models/task.js
var mongoose = require('mongoose');
var TaskSchema = new mongoose.Schema({
title: String,
create_at: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model("Task", TaskSchema);
This is to attach HTTP method request handlers using Express's router object for the webapp.
How to change my angular controller and node server code to post data into my database
Controller
var app= angular.module('App',[]);
var PD;
var address=null;
var pid=1;
app.controller("Ctrl",function($scope,$http) {
$http.get('/load').success(function(data) {
$scope.persons= data;
});
$scope.submit=function(){
PD=prompt("Enter person details");
if(PD.localeCompare("")!=0)
{
var data=JSON.stringify({pid:pid,
persondescription:PD,
url:$scope.url,
address:address,
submittedtime:new Date().toLocaleString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1"),
status:'Submitted'
});
console.log(data);
$http.post('/send',data).success(function(data,status) {
console.log(data);
console.log('Data posted successfully');
});
});
Node server code
Server
var express = require('express');
var http=require('http');
var bodyParser= require('body-parser');
var mysql = require('mysql');
var app = express();
app.set('port', 3000);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
enter code herevar connection = mysql.createConnection({
host : '-',
user : '-',
password : '-',
database : '-'
});
connection.connect(function(error){
if(error)
{
console.log("Problem with MySQL"+error);
}
else
{
console.log("Connected with Database");
}
});
app.get('/',function(req,res){
res.sendfile('managementt.html');
});
/*
* Here we will call Database.
* Fetch news from table.
* Return it in JSON.
*/
app.get('/load',function(req,res){
connection.query("SELECT * from personactivity",function(err,rows){
if(err)
{
console.log("Problem with MySQL"+err);
}
else
{
res.end(JSON.stringify(rows));
}
});
});
app.post('/send', function(req,res){
console.log(req.body);
var query = connection.query('insert into personactivity set ?',req.body, function(err, res) {
if (err) {
console.error(err);
return res.send(err);
} else {
return res.send('Ok');
}
});
app.listen(3000,function(){
console.log("It's Started on PORT 3000");
});
How to change my angular controller and node server code to post data into my database
I'm having trouble getting my head around $resource. I'm trying to apply a delete method to remove a MongoDB database entry when user presses a delete button. I am using Angular 1.4 with Express and Mongoose.
Here is my HTML:
<body ng-app="polls" ng-controller="PollsCtrl">
Polls:
<ul>
<li ng-repeat="question in questions">
{{ question.questionName }}
<button ng-click="deletePoll(question._id, $index)">Delete</button>
</li>
</ul>
...
Here's the client-side controller:
"use strict";
var app = angular.module('polls', ['ngResource']);
app.controller('PollsCtrl', function ($scope, $resource) {
var Poll = $resource('/api/polls');
var PollID = $resource('/api/polls/:pollID');
Poll.query(function (results) {
$scope.questions = results;
});
$scope.questions = [];
$scope.questionName = '';
$scope.addPoll = function () {
var poll = new Poll();
poll.questionName = $scope.questionName;
poll.$save(function (result) {
$scope.questions.push(result);
$scope.questionName = '';
});
};
$scope.deletePoll = function (id, index) {
var poll = new PollID();
poll.$remove(function () {
$scope.questions.splice(index, 1);
});
};
});
here's the server file including the remove method:
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
mongoose.connect('mongodb://localhost/poll-app');
app.use('/controllers', express.static(__dirname + '/controllers'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/polls', function (req, res) {
res.sendFile(path.join(__dirname + '/polls.html'));
});
app.get('/add-poll', function (req, res) {
res.sendFile(path.join(__dirname + '/add-poll.html'));
});
var pollSchema = new mongoose.Schema({questionName: String});
var Poll = mongoose.model('Poll', pollSchema);
var creater = function (req, res) {
var poll = new Poll(req.body);
poll.save(function (err, result) {
if (err) throw err;
res.json(result);
})
};
var list = function (req, res) {
Poll.find({}, function (err, result) {
if (err) throw err;
res.json(result);
});
};
var remove = function (req, res) {
console.log(req.params);
var poll = new Poll(req.body);
poll.remove({_id: req.params}, function (err, result) {
if (err) throw err;
res.json(result);
});
};
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.post('/api/polls', creater);
app.get('/api/polls', list);
app.delete('/api/polls/:pollID', remove);
app.listen(3000, function () {
console.log('HI');
});
I'm pretty sure the error lies in the server's remove() method. When i test this, i actually get:
DELETE http://localhost:3000/api/polls 404 (Not Found)
as though it isn't routing to where i want it to.
poll.$remove({pollID:id}, function () {
$scope.questions.splice(index, 1);
})
in your case, I think it's better to use $http:
$http.delete('/api/polls/pollID/'+req.params).
This way, you don't have to get the object before delete
My program is trying to add data to a PostgreSQL db on Heroku, but when I click the appropriate button it writes the data as "Undefined". Am I making a mistake in the way I call the variables?
The app is using Node.js. My approach for writing to the db was copied from from http://www.jitendrazaa.com/blog/webtech/how-to-use-postgresql-in-nodejs/, but I'm using Jade instead of html.
Here's the Jade page that shows the data and has a button to add to the db. The $scope.addRecord function is defined here:
extends layout
block content
div(id="container", ng-controller="postgreSQLCtrl")
h2 Your Business Card's Data
h3 You can edit any of the fields below. Just click on the field and type whatever you like. To add to the database click the button at the bottom.
p.lead Name:
input(value=name, id="name", maxlength="30", width="600", ng-model="name", type="text")
p.lead Description:
input(value=description, id="description", maxlength="30", width="600", ng-model="description", type="text")
p.lead Location:
input(value=location, id="location", maxlength="30", width="600", ng-model="location", type="text")
p.lead Company:
input(value=company, id="company", maxlength="30", width="600", ng-model="company", type="text")
p.lead Title:
input(value=jtitle, id="jtitle", maxlength="30", width="600", ng-model="jtitle", type="text")
p.lead URL for Your Photo:
input(value=photo, id="photo", maxlength="200", width="600", ng-model="photo", type="text")
img(src= photo)
| <button ng-click="addRecord()" id="btnAdd" name="btnAdd" class="btn btn-danger">Add to db</button>
script(src='//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js')
script.
var myApp = angular.module('postgreSQL',[ ]);
myApp.controller('postgreSQLCtrl', ['$scope' ,'$http', function($scope,$http) {
$scope.addRecord = function(){
var url = '/db/addRecord?name='+$scope.name+'&description='+$scope.description+'&location='+$scope.location+'&company='+$scope.company+'&jtitle='+$scope.jtitle+'&photo='+$scope.photo;
console.log(url);
$http({method: 'GET', url: '/db/addRecord?name='+$scope.name+'&description='+
$scope.description+'&location='+$scope.location+'&company='+
$scope.company+'&jtitle='+$scope.jtitle+'&photo='+$scope.photo}).
success(function(data, status) {
alert('Record Added');
});
}
}]);
Here is the app's main js file. A lot of this code deals with passport and might not be relevant.
var express = require('express');
var app = express();
var path = require('path');
// Express middleware
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var logger = require('morgan');
// Passport
var passport = require('passport');
var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy; // source of strategy: https://github.com/auth0/passport-linkedin-oauth2
var config = require('./config.json');
var pg = require('pg');
var http = require('http');
var request = require('request');
var dbOperations = require("./dbOperations.js");
var logFmt = require("logfmt");
// View engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Middleware
app.use(express.static('public')); // Put your static files here
app.use(cookieParser());
app.use(bodyParser());
app.use(session({ secret: 'shhhsupersecret' }));
app.use(passport.initialize());
app.use(passport.session());
// Logger
app.use(logger('dev'));
// heroku tells us to use this
/*
pg.connect(process.env.DATABASE_URL, function(err, client) {
if (err) throw err;
console.log('Connected to postgres! Getting schemas...');
client
.query('SELECT table_schema,table_name FROM information_schema.tables;')
.on('row', function(row) {
console.log(JSON.stringify(row));
});
});
*/
// Passport session setup.
// to support persistent login sessions, passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing. However, since this example does not
// have a database of user records, the complete LinkedIn profile is
// serialized and deserialized.
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
passport.use(new LinkedInStrategy({
clientID: config.LINKED_IN_CLIENT_ID,
clientSecret: config.LINKED_IN_CLIENT_SECRET,
callbackURL: "http://shrouded-reef-9087.herokuapp.com/auth/linkedin/callback",
scope: [ 'r_basicprofile' ],
passReqToCallback: true
}, function(req, accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
req.session.accessToken = accessToken;
process.nextTick(function () {
// To keep the example simple, the user's LinkedIn profile is returned to
// represent the logged-in user. In a typical application, you would want
// to associate the LinkedIn account with a user record in your database,
// and return that user instead.
done(null, profile);
});
}));
// Routes
app.get('/', function (req, res) {
res.render('index', {title: 'LinkedIn Test Authorization'});
});
/*
from http://www.jitendrazaa.com/blog/webtech/how-to-use-postgresql-in-nodejs/
app.get('/' , function(req,res) {
res.sendfile('views/index.html');
} );
*/
app.get('/db/readRecords', function(req,res){
dbOperations.getRecords(req,res);
});
app.get('/db/addRecord', function(req,res){
dbOperations.addRecord(req,res);
});
app.get('/db/delRecord', function(req,res){
dbOperations.delRecord(req,res);
});
app.get('/db/createTable', function(req,res){
dbOperations.createTable(req,res);
});
app.get('/db/dropTable', function(req,res){
dbOperations.dropTable(req,res);
});
app.get('/user', function(req, res) {
console.log('User Object: ', req.user);
var name = req.user.displayName;
var description = req.user._json.headline;
var location = req.user._json.location.name;
var company = req.user._json.positions.values[0].company.name;
var jtitle = req.user._json.positions.values[0].title;
var photo = req.user.photos[0];
console.log('-----Desired data: ',name,description,location,company,jtitle,photo);
console.log('-----Desired data length: ',name.length,description.length,location.length,company.length,jtitle.length,photo.length);
res.render('user', {name: name, description: description, location: location, company: company, jtitle: jtitle, photo: photo, title: 'Your Business Card'});
});
// This sends the user to authenticate with linked-in
app.get('/auth/linkedin',
passport.authenticate('linkedin', { state: 'asdfqwertlkjhz91xcv' }),
function(req, res){
// The request will be redirected to LinkedIn for authentication, so this
// function will not be called.
});
// This is where we handle the callback and redirect the user
app.get('/auth/linkedin/callback',
passport.authenticate('linkedin', { failureRedirect: '/' }),
function (req,res) {
res.redirect('/user');
});
// The server
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('LinkedIn Test app listening at http://%s:%s', host, port);
});
This is the dbOperations.js file, which defines the "addRecord" function that I'm trying to call with the angular $scope.addRecord function.
module.exports = {
getRecords: function(req, res) {
var pg = require('pg');
//You can run command "heroku config" to see what is Database URL from Heroku belt
var conString = process.env.DATABASE_URL || "postgres://postgres:Welcome123#localhost:5432/postgres";
var client = new pg.Client(conString);
client.connect();
var query = client.query("select * from cards");
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
client.end();
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(JSON.stringify(result.rows, null, " ") + "\n");
res.end();
});
},
addRecord : function(req, res){
var pg = require('pg');
console.log("--------------req=",req);
var conString = process.env.DATABASE_URL || "postgres://postgres:Welcome123#localhost:5432/postgres";
var client = new pg.Client(conString);
client.connect();
var query = client.query("insert into cards (name,description,location,company,jtitle,photo) "+
"values ('"+req.name+"','"+req.description+"','"+
req.location+"','"+req.company+
"','"+req.jtitle+"','"+req.photo+
"')");
query.on("end", function (result) {
client.end();
res.write('Success');
res.end();
});
},
delRecord : function(req, res){
var pg = require('pg');
var conString = process.env.DATABASE_URL || "postgres://postgres:Welcome123#localhost:5432/postgres";
var client = new pg.Client(conString);
client.connect();
var query = client.query( "Delete from cards Where id ="+req.query.id);
query.on("end", function (result) {
client.end();
res.write('Success');
res.end();
});
},
createTable : function(req, res){
var pg = require('pg');
var conString = process.env.DATABASE_URL || "postgres://postgres:Welcome123#localhost:5432/postgres";
var client = new pg.Client(conString);
client.connect();
var query = client.query( "CREATE TABLE cards"+
"("+
"name character varying(50),"+
"description character varying(50),"+
"location character varying(50),"+
"company character varying(50),"+
"jtitle character varying(50),"+
"photo character varying(200),"+
"id serial NOT NULL"+
")");
query.on("end", function (result) {
client.end();
res.write('Table Schema Created');
res.end();
});
},
dropTable : function(req, res){
var pg = require('pg');
var conString = process.env.DATABASE_URL || "postgres://postgres:Welcome123#localhost:5432/postgres";
var client = new pg.Client(conString);
client.connect();
var query = client.query( "Drop TABLE cards");
query.on("end", function (result) {
client.end();
res.write('Table Schema Deleted');
res.end();
});
}
};
(This is an edited version of the original. At first the function wasn't working due to a misplaced ' symbol.)
In addRecord change it to req.query.name etc. instead of req.name.
I'm new to the stack and am building a test page to sort out my understanding before building my actual project. Right now, I'm just trying to take user input, save it to a database, and print it. The data should be saved in a basic Mongoose model, test. While all of the routes are open, instead of printing what the user entered it prints something in the following format:
{"_id":"55c3925b48b9dba0d896be40","__v":0}
I suspect it has something to do with the second line of this snippet from index.js:
router.post('/survey', function(req, res, next) {
var test = new Test(req.body);
test.save(function(err,test) {
if(err) {
return next(err);
}
res.json(test);
});
});
module.exports = router;
Relevent code:
All of index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
//set up routes
var mongoose = require('mongoose');
var Test = mongoose.model('Test');
router.get('/survey', function(req, res, next) {
Test.find(function(err, tests) {
if(err) {
return next(err);
}
res.json(tests);
});
});
router.post('/survey', function(req, res, next) {
var test = new Test(req.body);
test.save(function(err,test) {
if(err) {
return next(err);
}
res.json(test);
});
});
module.exports = router;
Tests.js (model):
var mongoose = require('mongoose');
var TestSchema = new mongoose.Schema({
'name': String,
});
module.exports = mongoose.model('Test', TestSchema);
Relevant bits of angular code:
routerApp.factory('tests', ['$http', function($http){
var o = {
tests: []
};
o.getAll = function() {
return $http.get('/survey').success(function(data){
console.log('get all sees data as:' + data);
angular.copy(data, o.tests);
});
};
o.create = function(test) {
console.log('create sees test as' + test);
return $http.post('/survey', test).success(function(data){
o.tests.push(data);
console.log('Data:' + data);
});
};
return o;
}]);
routerApp.controller('FormCtrl', ['$scope', 'tests',
function($scope, tests){
$scope.test = tests.tests;
$scope.addTest = function(){
if(!$scope.text || $scope.text === '') { return; }
tests.create({
name: $scope.text
});
$scope.text = '';
};
}
]);
I suspect this is a matter of not understanding what kind of object req is, but I'm not entirely positive. How would I go about making this code save data in the format described in the mongoose model?
If you call .toObject() on the document object (res.json(test.toObject())), you should get a plain object back containing the data in that document.
Try to console.log(req.body). If it's empty, then try adding app.use(bodyParser.json()) somewhere before your routes are defined (and be sure to install it with npm and require it first).
When you POST some sort of JSON, it isn't available in req.body by default. You need bodyParser to parse the incoming data and make it available in req.body. See https://medium.com/#adamzerner/how-bodyparser-works-247897a93b90 for more info.