meaning of parameters of function such as “/” res,req,next - angularjs

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.

Related

"TypeError: Contact is not a constructor" when I check post json data in Postman

When I run node app.js it works, and does not give any error. But when I route localhost:3000/api/contact and post json to check via Postman it gives that error.
I have seen some other releted question but cannot fiqure out.
Here is my app.js
//importing modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//connect to mongodb
mongoose.connect('mongodb://localhost:27017/contactlist');
//connection on
mongoose.connection.on('connected',()=>{
console.log('Database connected');
});
mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('Error in database'+err);
}
});
//path port
const port = 3000;
//adding middleware
app.use(cors());
//body-parser
app.use(bodyparser.json());
//static path
app.use(express.static(path.join(__dirname,'public')));
//add route
app.use('/api',route);
//testing server
app.get('/',(req,res)=>{
res.send('foobar');
});
app.listen(port,()=>{
console.log('server is started at port:'+port);
});
Here is my route.js
const express = require('express');
const router = express.Router();
const Contact = require('../models/contacts');
//get data
router.get('/contacts', (req, res, next)=>{
Contact.find(function(err, contacts){
res.json(contacts);
});
});
//add data
router.post('/contact',(req, res, next)=>{
let newContact = new Contact({
first_name: req.body.first_name,
last_name: req.body.last_name,
phone_num: req.body.phone_num
});
newContact.save((err, contact)=>{
if(err)
{
res.json({msg: 'Failed to add contact'});
}
else
{
res.json({msg: 'Contact add succesfuly'});;
}
});
});
//delete data
router.delete('/contact/:id', (req, res, next)=>{
Contact.remove({_id: req.params.id}, function(err, result){
if(err)
{
res.json(err);
}
else
{
res.json(result);
}
});
});
module.exports = router;
I am a new node js learner. I cant understand what is the problem please help me. Thanks in advance!
Take a look at the code below:
// your schema and model
// should look similar to below
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var ContactSchema = new Schema({
first_name: String,
last_name: String,
phone_num: String
});
const Contact = mongoose.model('Contact', ContactSchema);
module.exports = Contact;
Maybe you forgot to use mongoose.model?

Getting "TypeError: Cannot read property 'collection' of undefined"

Below attach folder directory, server.js and api.js file. Program is not running, give me error like:
ReferenceError: dbo is not defined
at C:\shivapp\mean_app\mandiapp\server\api.js:18:1
at Layer.handle [as handle_request] (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\layer.js:95:5)
at next (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\layer.js:95:5)
at C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:335:12)
at next (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:174:3)
at router (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:47:12).
Folder directory
File-> server.js
var express=require('express');
var bodyParser=require('body-parser');
var path=require('path');
var http = require('http');
var app=express();
var api= require('./server/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'dist')));
app.use('/',api);
//8376884527
app.get('*'),(req,res) => {
res.sendFile(path.join(__dirname,'dist/index.html'));
}
var port= process.env.port || '3000';
app.set('port',port);
var server = http.createServer(app);
server.listen(port,()=>console.log('server running...'));
file -> api.js
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var dbo;
MongoClient.connect("mongodb://localhost:27017/mandiapp", function(err, db) {
if(err) throw err;
var dbo = db.db("mandiapp");
});
router.get('/users', function(req, res) {
dbo.collection("user").find({}).toArray(function(err, result) {
if (err) throw err;
res.json(result);
//dbo.close();
})
})
router.get('/recent', function(req, res) {
var collection = db.get().collection('comments')
collection.find().sort({'date': -1}).limit(100).toArray(function(err, docs) {
res.render('comments', {comments: docs})
})
})
module.exports = router
The error you're seeing is because variable dbo is not defined, as error suggests.
Your issue is the following code:
MongoClient.connect("mongodb://localhost:27017/mandiapp", function(err, db) {
if(err) throw err;
var dbo = db.db("mandiapp");
});
You have defined variable dbo inside a callback function which will not be available outside of this scope. You should define it else where and assign to it here.
See below for fix if unclear.
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var dbo = undefined;
MongoClient.connect("mongodb://localhost:27017/mandiapp", function(err, db) {
if(err) throw err;
dbo = db.db("mandiapp");
});
router.get('/users', function(req, res) {
dbo.collection("user").find({}).toArray(function(err, result) {
if (err) throw err;
res.json(result);
//dbo.close();
})
})
router.get('/recent', function(req, res) {
var collection = db.get().collection('comments')
collection.find().sort({'date': -1}).limit(100).toArray(function(err, docs) {
res.render('comments', {comments: docs})
})
})
module.exports = router
You have more undefiend variables which you will be looking for later on in your code such as collection and db in your /recent get handler.
Please check link
remove line : var dbo = db.db("mandiapp");
var db = MongoClient.connect('mongodb://localhost:27017/mandiapp', function(err, db) {
if(err)
throw err;
console.log("connected to the mongoDB !");
});
db.collection("user").find({}).toArray(function(err, result) {
if (err) throw err;
res.json(result);
//dbo.close();
})
})

How to properly call an external api to use from within express application to build my own restful api?

I'am trying to create a restful api but I need to use an external api quandl to build my api, when i try to use my api from the client(built in angularjs) i get a 500 internal server error and No default engine was specified and no extension was provided in command line. i know my api work cause i tested it with postman, its just not working from the client.
I tried looking at this post : express js 4 how to serve json results without rendering any views /css but it wasnt helpful.
module.exports = function(io){
var q = require('q');
var request = require('request');
var mongoose = require('mongoose');
var Stock = mongoose.model('Stock');
var base_url = "https://www.quandl.com/api/v3/datasets/WIKI/";
var dotjson = ".json"
var apiKey = "?api_key=" + process.env.quandl_apiKey;
function sendJsonResponse(res,status,content){
res.status(status);
res.json(content);
}
// get stock data using quandl api
function stockData(name){
var deferred = q.defer();
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
var date = d.getDate();
request({
url: base_url + name + dotjson + apiKey,
qs:{
start_date:(year-1) + '-' + month + '-' + date,
end_date:year + '-' + month + '-' + date
}
},function(error,response,body){
if(error){
deferred.reject('Error: ' + error);
}else if(response.statusCode !== 200){
deferred.reject('Invalid Status Code: ' + response.statusCode);
}else{
deferred.resolve(body);
}
})
return deferred.promise;
}
// get stock data that is stored in database
function getStockInDatabase(req,res){
Stock.find({},function(err,stock){
if(err){
sendJsonResponse(res,404,err);
} else {
sendJsonResponse(res,200,stock);
}
})
}
// create stock data to be stored in database
function createStockData(req,res){
var stockDatas;
stockData(req.body.name.toUpperCase())
.then(function(stock){
stockDatas = JSON.parse(stock);
Stock.create({
name:stockDatas.dataset.name,
symbol:stockDatas.dataset.dataset_code
},function(err,stk){
if(err){
sendJsonResponse(res,400,err)
}else{
sendJsonResponse(res,201,stk);
io.emit('stock',stockDatas);
}
})
})
.catch(function(err){
sendJsonResponse(res,404,err);
})
}
// delete stock data in database
function deleteStockData(req,res){
Stock
.findByIdAndRemove(req.body._id)
.exec(function(err,stock){
if(err){
sendJsonResponse(res,404,err);
}else {
sendJsonResponse(res,204,null);
}
})
}
return {
getStockInDatabase:getStockInDatabase,
createStockData:createStockData,
deleteStockData:deleteStockData
}
}
angular service to use api:
(function(){
'use strict'
angular
.module('app.common')
.factory('stockService',stockService);
stockService.$inject = ['$http'];
function stockService($http){
function getStock(){
return $http.get('/api/stocks');
}
function getStockInDatabase(){
return $http.get('api/stocks/database');
}
function createStock(data){
return $http.post('/api/stocks',data);
}
function deleteStock(data){
return $http.delete('/api/stocks',data);
}
return{
getStockInDatabase:getStockInDatabase,
createStock:createStock,
deleteStock:deleteStock
}
}
})()
app.js configuration
require('dotenv').load();
var express = require('express');
var socketio = require('socket.io');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var io = socketio();
require('./api/models/db');
var app = express();
app.io = io;
var apiRoute = require('./api/routes/index')(io);
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(express.static(path.join(__dirname, 'client')));
app.use('/api', apiRoute);
app.use(function(req, res) {
res.sendFile(path.join(__dirname, 'client', 'index.html'));
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500).send({
message: err.message,
error: {}
})
});
module.exports = app;
No default engine specified error comes when you have not specified any content serving engine in express.. for you views or html files.
Try using
app.set('views', 'html page location');
app.set('view engine', 'jade');
You might have to additionally require jade.

How to add a new object with AngularJS and mongoDB

I'm using NodeJS, ANgularJS, and MongoDB with mongoose to make a website. I'm having some trouble adding an object in mongoDB. The name of the object is Todo.
Here are the models of Todo:
var mongoose = require('mongoose');
var TodoSchema = new mongoose.Schema({
name: String,
password : String,
completed: Boolean,
note: String
});
module.exports = mongoose.model('Todo', TodoSchema);
In the controller I create a new Todo and push it
angular.module('app').controller('Connexion', ['$scope', 'Todos','$location', function($scope,Todos, $location) {
$scope.editing = [];
$scope.todos = Todos.query();
$scope.save = function() {
var todo = new Todos({ name: "test", password: "test", completed: false });
$scope.todos.push(todo);
Todos.save($scope.todo);
}
}]);
This is my html page, each time I click on the button I Have a new todo created and it's displayed on screen:
<button ng-click="save()">Creer POST </button>
<ul>
<li ng-repeat="todo in todos">
{{todo.name}}
{{todo.password}}
</li>
</ul>
But I have a problem, the new object is not added on the database. How can I do it?
This is my files in the back-end :
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');
/* GET /todos listing. */
router.get('/', function(req, res, next) {
Todo.find(function (err, todos) {
if (err) return next(err);
res.json(todos);
});
});
/* POST /todos */
router.post('/', function(req, res, next) {
Todo.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /todos/id */
router.get('/:id', function(req, res, next) {
Todo.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /todos/:id */
router.put('/:id', function(req, res, next) {
Todo.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /todos/:id */
router.delete('/:id', function(req, res, next) {
Todo.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
And if this can help this the back-end file app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var Post = require('./models/Post.js');
var routes = require('./routes/index');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todoApp', function(err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
var app = express();
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('/', function(req, res, next){
res.sendFile(__dirname + '/public/index.html');
});
var found = ['DB Connection not yet established. Try again later. Check the console output for error messages if this persists.'];
module.exports = app;
$scope.todo from Todos.save($scope.todo); is not defined so this is why you might not manage to save anything

HTTP Post not connecting with angular

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.

Resources