Node.js Express Restful Api cannot get angular http post json - javascript

I have been having trouble accessing the data that is passed to express restful service from angular http service.(i build this web app with angular + node + express + mongodb)
While I using angular to post data to rest service, it cannot get my post json data, but when I using POSTMAN to post the data then it is working....
how can it be ?
is anything I missing in restful server side??
this is reply when angular post json
{
__v: 0,
_id: "59e854e9895ea424b40471a9",
updateTime: "2017-10-19T07:31:53.301Z",
createTime: "2017-10-19T07:31:53.301Z"
}
this is reply when postman post json
{
"__v": 0,
"uuid": "123",
"major": 10029,
"minor": 18910,
"bluetoothAddress": "123",
"createBy": "root",
"updateBy": "root",
"_id": "59e852ab4297be32902bae1d",
"updateTime": "2017-10-19T07:22:19.417Z",
"createTime": "2017-10-19T07:22:19.417Z"
}
this is my angular side code
controller.js
$scope.submitNewIbeacon = function() {
let data = {
uuid: $scope.inputUUID,
major: parseInt($scope.inputMajor),
minor: parseInt($scope.inputMinor),
bluetoothAddress: $scope.inputBluetoothAddress,
createBy: $scope.loginUser,
updateBy: $scope.loginUser
}
IbeaconListService.create_a_ibeacon(data)
.then(
function(response) {
var newIBeacon = response.data;
});
}
service.js
app.service('IbeaconListService', ['$http', '$q', function($http, $q) {
var BASEURL = "http://localhost:3000";
this.create_a_ibeacon = function(data) {
var deferred = $q.defer();
var config = {
headers: {
'Content-Type': 'application/json;charset=utf-8;'
}
}
$http.post(BASEURL + "/ibeacons", data, config)
.then(function(data) {
deferred.resolve(data);
}, function(error) {
deferred.reject(error);
})
return deferred.promise;
}
}]);
and this is my nodejs code
server.js
const express = require('express'),
app = express(),
port = process.env.PORT || 3000,
fileUpload = require('express-fileupload'),
cors = require('cors'),
mongoose = require('mongoose'),
ibeacon = require('./api/models/ibeaconListModel'),
area = require('./api/models/areaListModel'),
bodyParser = require('body-parser');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
// connect to MongoDB and create/use database called IbeaconDB
mongoose.connect('mongodb://localhost/IbeaconDB');
//importing route
var ibeaconRoutes = require('./api/routes/ibeaconListRoutes.js');
var areaRoutes = require('./api/routes/areaListRoutes.js');
//register the route
ibeaconRoutes(app);
areaRoutes(app);
app.listen(port);
console.log('ibeacon RESTful API server started on: ' + port);
app.use(function(req, res) {
res.status(404).send({ url: req.originalUrl + ' not found' })
});
ibeaconListModel.js
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var IbeaconSchema = new Schema({
uuid: {
type: String
},
major: {
type: Number
},
minor: {
type: Number
},
bluetoothAddress: {
type: String
},
createBy: {
type: String
},
createTime: {
type: Date,
default: Date.now
},
updateBy: {
type: String
},
updateTime: {
type: Date,
default: Date.now
}
});
// create a model based on the schema
module.exports = mongoose.model('Ibeacons', IbeaconSchema);
ibeaconListRoutes.js
'use strict';
module.exports = function(app) {
var ibeaconList = require('../controllers/ibeaconListController');
// ibeaconList Routes
app.route('/ibeacons')
.get(ibeaconList.list_all_ibeacons)
.post(ibeaconList.create_a_ibeacon);
app.route('/ibeacons/:ibeaconId')
.get(ibeaconList.read_a_ibeacon)
.put(ibeaconList.update_a_ibeacon)
.delete(ibeaconList.delete_a_ibeacon);
};
ibeaconListController.js
'use strict';
var mongoose = require('mongoose'),
Ibeacon = mongoose.model('Ibeacons');
exports.list_all_ibeacons = function(req, res) {
Ibeacon.find({}, function(err, ibeacon) {
if (err)
res.send(err);
res.json(ibeacon);
});
};
exports.create_a_ibeacon = function(req, res) {
const doc = {
uuid: req.body.uuid,
major: req.body.major,
minor: req.body.minor,
bluetoothAddress: req.body.bluetoothAddress,
updateBy: req.body.updateBy,
createBy: req.body.createBy
}
var new_ibeacon = new Ibeacon(doc);
console.log(new_ibeacon);
new_ibeacon.save(function(err, ibeacon) {
if (err)
res.send(err);
res.json(ibeacon);
});
};
exports.read_a_ibeacon = function(req, res) {
Ibeacon.findById(req.params.ibeaconId, function(err, ibeacon) {
if (err)
res.send(err);
res.json(ibeacon);
});
};
exports.update_a_ibeacon = function(req, res) {
const doc = {
uuid: req.body.uuid,
major: req.body.major,
minor: req.body.minor,
bluetoothAddress: req.body.bluetoothAddress,
updateBy: req.body.updateBy,
updateTime: Date.now()
}
Ibeacon.findOneAndUpdate({ _id: req.params.ibeaconId }, doc, { new: true }, function(err, ibeacon) {
if (err)
res.send(err);
res.json(ibeacon);
});
};
exports.delete_a_ibeacon = function(req, res) {
Ibeacon.remove({
_id: req.params.ibeaconId
}, function(err, ibeacon) {
if (err)
res.send(err);
res.json({ message: 'Ibeacon successfully deleted' });
});
};
Update 10:29pm
I use custom middleware to check my request, then I found that my http method is GET ( it suppose to be POST )
Custom Middleware
app.use((req,res,next) => {
console.log(req);
next();
});
very confused ##

Related

Node js & mongo API : Error: socket hang up

Im trying to make an API with node JS (express and jwt) with a mongodb.
I've make some routes (like to get markers for example), that's working fine.
BUT i've also make a route in order to post some markers. When I query it (that takes long time, and with Postman), and I've an error like :
"Could not get any response"
and in my console :
Error: socket hang up
My route controller :
const model = require('../models/markers');
module.exports = {
create: function(req, res, next) {
model.create({
param_1: req.body.param_1,
param_2: req.body.param_2,
param_3: req.body.param_3,
}, function (err, result) {
if (err)
next(err);
else
res.json({status: "success", message: "Marker added successfully", data: null});
});
},
getAll: function(req, res, next) {
let list = [];
model.find({}, function(err, items){
if (err){
next(err);
} else{
for (let item of items) {
list.push({
id: item._id,
param_1: item.param_1,
param_2 : item.param_2,
param_3: item.param_3
});
}
res.json({status:"success", message: "Markers list found", data:{markers: list}});
}
});
},
};
And for my route :
const express = require('express');
const router = express.Router();
const markerController = require('../controllers/markers');
router.get('/', markerController.getAll);
router.post('/', markerController.create);
module.exports = router;
My model :
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MarkerSchema = new Schema({
param_1: {
type: String,
required: true
},
param_2: {
type: String,
},
param_3: {
type: [{
type: String,
enum: ['0.5', '1', ',1.25', '1.5', '2', '3+']
}],
default: ['pending']
}
});
module.exports = mongoose.model('Marker', MarkerSchema);
My get router works fine but my post route don't.
You should check #Will Alexander comment, if it's a copy paste you have a typo in:
param_2: req.bodyparam_2,

Stripe cannot create Ephemeral Key

I am making an iOS project which uses Stripe. I am using a STPCustomerContext and the parameter to create an instance is an object of MainAPI below. When I create the instance, it automatically calls createCustomerKey() but an error (404) is throwing. The URL is "http://localhost:1337/ephemeral_keys" and I believe that is what I have everywhere but yet it is throwing a 404. Here is the code for MainAPI.swift, index.js, & api.js.
The code is:
MainAPI.swift
class MainAPI:NSObject, STPEphemeralKeyProvider {
// override init(){}
static let shared = MainAPI()
var baseURLString = Constants.BASE_URL
// MARK: STPEphemeralKeyProvider
enum CustomerKeyError: Error {
case missingBaseURL
case invalidResponse
}
func createCustomerKey(withAPIVersion apiVersion: String, completion: #escaping STPJSONResponseCompletionBlock) {
// the request
func request(id: String) {
print("creating a eph key request with customerId: \(id)") // good
let url = self.baseURLString.appending("/ephemeral_keys")
Alamofire.request(url, method: .post, parameters: [
"api_version": apiVersion,
"customerId": id
])
.validate(statusCode: 200..<300)
.responseJSON { responseJSON in
switch responseJSON.result {
case .success(let json):
print("created customer ephemeral key!")
completion(json as? [String: AnyObject], nil)
case .failure(let error):
print("could not customer ephemeral key!\n Error info: ")
print(error.localizedDescription)
completion(nil, error)
}
}
}
print("attempting to create customer ephemeral key . . .(createCustomerKey())")
let customerId = . . . // get customer id
request(id: costumerId) // this passes on the CORRECT customerId each time
}
}
api.js
var express = require('express')
var router = express.Router()
var stripe_key = process.env.STRIPE_KEY || "sk_test_myTestKey"
var stripe = require('stripe')(stripe_key);
var request = require("request-promise-native")
//API
router.get('/', function (req, res) {
res.status(200).send(JSON.stringify({ message: 'API Gateway', success: true, error: null }));
}) // Just for testing, just for error-handling
//1. Create a customer account
router.post('/new_customer', function (req, res) {
console.log("Creating new customer account...")
var body = req.body
stripe.customers.create({ email: body.email, })
.then((customer) => {
console.log(customer)
// Send customerId -> Save this for later use
res.status(200).send(JSON.stringify({ success: true, error: null, customerId: customer.id }));
})
.catch((err) => {
console.log(err)
res.status(400).send(JSON.stringify({ success: false, error: err }))
});
})
//2. Save Credit Card with token
router.post('/new_card', function (req, res) {
var customerId = req.body.customerId
var token = req.body.token
stripe.customers.update(customerId, { source: token })
.then((customer) => {
console.log(customer)
res.status(200).send(JSON.stringify({ success: true, error: null }));
})
.catch((err) => {
console.log(err)
res.status(400).send(JSON.stringify({ success: false, error: err }))
});
})
//3. Use customerId to post a charge
router.post('/new_charge', function (req, res) {
var customerId = req.body.customerId
var amount = req.body.amount
var source = req.body.source
stripe.charges.create({
amount: amount, //in cents
currency: "usd",
customer: customerId, //CUSTOMER_STRIPE_ACCOUNT_ID
source: source, // obtained with Stripe.js
}).then((charge) => {
res.status(200).send(JSON.stringify({ message: 'Sucess.', success: true, error: null }));
}).catch((error) =>{
res.status(400).send(JSON.stringify({ message: 'Error', success: false, error: error }));
})
})
// here is the error I am assuming
router.post('/ephemeral_keys', (req, res) => {
const stripe_version = req.body.api_version;
var customerId = req.body.customerId;
if (!stripe_version) {
res.status(400).end();
return;
}
console.log(stripe_version)
// This function assumes that some previous middleware has determined the
// correct customerId for the session and saved it on the request object.
stripe.ephemeralKeys.create(
{customer: customerId},
{stripe_version: stripe_version}
).then((key) => {
console.log("Ephemeral key: " + key)
res.status(200).json(key);
res.status(200).send(JSON.stringify({ message: 'AAAAhh', success: true, error: null }));
}).catch((err) => {
console.log("Ephemeral key error: " + err)
res.status(200).send(JSON.stringify({ message: 'ABBBBBB', success: true, error: null }));
res.status(500).end();
});
});
module.exports = router;
index.js
//Environment Vars
var uri = process.env.NODE_ENV || "development"
console.log(uri + " environment")
//Express App
var express = require('express');
var app = express();
//Api for reading http post request body in express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
//Log Connections
app.use(function timeLog (req, res, next) {
console.log('incoming connection . . . ')
next()
})
//API middelware
var api = require('./api')
app.use('/api', api)
app.get('/', function (req, res) {
res.status(200).send(JSON.stringify({ message: 'Welcome!', success: true, error: null }));
});
//Create Server
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function () {
console.log('server running on port ' + port + '.');
});
When I create a STPCustomerContext (like this):
let apiKeyObject = MainAPI.shared
customerContext = STPCustomerContext(keyProvider: apiKeyObject)
The following error prints (not allowing the STPPaymentContext later to display):
Response status code was unacceptable: 404.
Please try with the below nodejs code, because syntax which your code is using might not be correct, I was using the same code as you, but later changed the implementation & deployed to firebase CLI
exports.createEphemeralKeys = functions.https.onRequest((req, res) => {
var api_version = req.body.api_version;
var customerId = req.body.customerId;
if (!api_version) {
res.status(400).end();
return;
}
stripe.ephemeralKeys.create(
{ customer: customerId },
{ stripe_version: api_version },
function(err, key) {
return res.send(key);
});
});
You might get below kind of logs.
{
id: 'ephkey_1BramAFjruqsvjkVQGdZLiV5',
object: 'ephemeral_key',
associated_objects: [ { type: 'customer', id: 'cus_CEPMtLbshv7EaP' } ],
created: 1517701830,
expires: 1517705430,
livemode: false,
secret: 'ek_test_YWNjdF8xQmxUb0FGanJ1cXN2amtWLHVPcUdMN3d4UEhncW1sQkNJYmlOdzhwUGdjVUxOd1Y'
}
For .swift file
Please Click here
Please have a look at https://www.youtube.com/watch?v=NdszUvzroxQ
I believe you need to use some remote server, instead of local server,
In my Swift file I am using .responseString instead of .responseJSON by this is I am getting success but the response is a HTML file of requesting Google Signin

Why I get a null or [ ] response from my server.js file?

I have been doing an example based on the TV showTracker and So far I couldn't get any shows into my website. I have been trying so hard to whether I have made a mistake but I still couldn't find anything. So How to I retrieve these information. I have stared this server.js and mongod in separate CMDs and gulp in another CMD I still couldn't get any of the shows. When I see the responses it will show a blank array "[]" like this. So any advice? Help would be most appreciated. (I have host the website yet, thought this would help also to my question). The error in the net debugger says api/shows/ - response = [ ]
Here is my server.jsrespone
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var showSchema = new mongoose.Schema({
_id: Number,
name: String,
airsDayOfWeek: String,
airsTime: String,
firstAired: Date,
genre: [String],
network: String,
overview: String,
rating: Number,
ratingCount: Number,
status: String,
poster: String,
subscribers: [{
type: mongoose.Schema.Types.ObjectId, ref: 'User'
}],
episodes: [{
season: Number,
episodeNumber: Number,
episodeName: String,
firstAired: Date,
overview: String
}]
});
var userSchema = new mongoose.Schema(
{
email: { type: String, unique: true },
password: String
});
userSchema.pre('save', function (next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, function (err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function (candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
}
var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);
mongoose.connect('localhost');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
app.get('/api/shows', function (req, res, next) {
var query = Show.find();
if (req.query.genre) {
query.where({ genre: req.query.genre });
} else if (req.query.alphabet) {
query.where({ name: new RegExp('^' + '[' + req.query.alphabet + ']', 'i') });
} else {
query.limit(12);
}
query.exec(function (err, shows) {
if (err) return next(err);
res.send(shows);
});
});
app.get('/api/shows/:id', function (req, res, next) {
Show.findById(req.params.id, function (err, show) {
if (err) return next(err);
res.send(show);
});
});
app.post('/api/shows', function (req, res, next) {
var apiKey = 'E36B52F7E036AFF3';
var seriesName = req.body.showName
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
var parser = xml2js.Parser({
explicitArray: false,
normalizeTags: true
});
async.waterfall([
function (callback) {
request.get('http://thetvdb.com/api/GetSeries.php?seriesname=' + seriesName, function (error, response, body) {
if (error) return next(error);
parser.parseString(body, function (err, result) {
if (!result.data.series) {
return res.send(404, { message: req.body.showName + ' was not found.' });
}
var seriesId = result.data.series.seriesid || result.data.series[0].seriesid;
callback(err, seriesId);
});
});
},
function (seriesId, callback) {
request.get('http://thetvdb.com/api' + apiKey + '/series/' + seriesId + '/all/en.xml', function (error, response, body) {
if (error) return next(error);
parser.parseString(body, function (err, result) {
var series = result.data.series;
var episodes = result.data.episode;
var show = new Show({
_id: series.id,
name: series.seriesname,
airsDayOfWeek: series.airs_dayofweek,
airsTime: series.airs_time,
firstAired: series.firstaired,
genre: series.genre.split('|').filter(Boolean),
network: series.network,
overview: series.overview,
rating: series.rating,
ratingCount: series.ratingcount,
runtime: series.runtime,
status: series.status,
poster: series.poster,
episodes: []
});
_.each(episodes, function (episode) {
show.episodes.push({
season: episode.seasonnumber,
episodeNumber: episode.episodenumber,
episodeName: episode.episodename,
firstAired: episode.firstaired,
overview: episode.overview
});
});
callback(err, show);
});
});
},
function (show, callback) {
var url = 'http://thetvdb.com/banners/' + show.poster;
request({ url: url, encoding: null }, function (error, response, body) {
show.poster = 'data:' + response.headers['content-type'] + ';base64,' + body.toString('base64');
callback(error, show);
});
}
], function (err, show) {
if (err) return next(err);
show.save(function (err) {
if (err) {
if (err.code == 11000) {
return res.send(409, { message: show.name + ' already exists.' });
}
return next(err);
}
res.send(200);
});
});
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) next();
else res.send(401);
};
app.use(function (req, res, next) {
if (req.user) {
res.cookie('user', JSON.stringify(req.user));
}
next();
});
app.get('*', function (req, res) {
res.redirect('/#' + req.originalUrl);
})
app.use(function (err, req, res, next) {
console.error(err.stack);
res.send(500, { message: err.message });
});
Change var query = Show.find(); in /api/shows to
var query = Show.find(function(err, showdata){
// all the checking and the res.send(shows) goes here
})
Just wait for data and do all the operation(asynchronous)
OK Guys, I finally found the answer to the question. It's nothing wrong with the script (server.js). It is because I think it cannot hold the data in the database ('localhost:27017/test'). That is why maybe I'm getting a null response from the TVDB API. Once I changed my database and connect strings to (
'mongodb://nixsiow:abcd1234#ds027479.mongolab.com:27479/nixshowtrackrapp'
, It worked like a charm.
So maybe my answer may not explain this properly, or you can look for more details in stack overflow. Thanks for the help guys. I hope that this will help who try to do this tutorial and get stuck on this step.
So final Answer:
mongoose.connect('mongodb://nixsiow:abcd1234#ds027479.mongolab.com:27479/nixshowtrackrapp');
var agenda = require('agenda')({ db: { address: 'mongodb://nixsiow:abcd1234#ds027479.mongolab.com:27479/nixshowtrackrapp' } });
Also Nixsow's website may have a help, it is the most recent update that I found for this tutorial.

Express js routing error ("Cannot GET /")

I am having a hard time wondering why, when i access my HTTP server http://localhost:8000/, i get a "Cannot GET /" message. I use express js for routing server side and angular at client-side.
I have read that this error is there because i haven't set a route for "/" path, but i don't want to route anything there, just want to let my angular handle "/".
FYI, my express server is in a different path than the angular app.
MY node code:
var bcrypt = require('bcryptjs');
var bodyParser = require('body-parser');
var cors = require('cors');
var express = require('express');
var jwt = require('jwt-simple');
var moment = require('moment');
var mongoose = require('mongoose');
var path = require('path');
var request = require('request');
var compress = require('compression');
var config = require('./config');
var User = mongoose.model('User', new mongoose.Schema({
instagramId: { type: String, index: true },
email: { type: String, unique: true, lowercase: true },
password: { type: String, select: false },
username: String,
fullName: String,
picture: String,
accessToken: String
}));
mongoose.connect(config.db);
var app = express();
app.set('port', process.env.PORT || 8000);
app.use(compress());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 2628000000 }));
/*
|--------------------------------------------------------------------------
| Login Required Middleware
|--------------------------------------------------------------------------
*/
function isAuthenticated(req, res, next) {
if (!(req.headers && req.headers.authorization)) {
return res.status(400).send({ message: 'You did not provide a JSON Web Token in the Authorization header.' });
}
var header = req.headers.authorization.split(' ');
var token = header[1];
var payload = jwt.decode(token, config.tokenSecret);
var now = moment().unix();
if (now > payload.exp) {
return res.status(401).send({ message: 'Token has expired.' });
}
User.findById(payload.sub, function(err, user) {
if (!user) {
return res.status(400).send({ message: 'User no longer exists.' });
}
req.user = user;
next();
})
}
/*
|--------------------------------------------------------------------------
| Generate JSON Web Token
|--------------------------------------------------------------------------
*/
function createToken(user) {
var payload = {
exp: moment().add(14, 'days').unix(),
iat: moment().unix(),
sub: user._id
};
return jwt.encode(payload, config.tokenSecret);
}
/*
|--------------------------------------------------------------------------
| Sign in with Email
|--------------------------------------------------------------------------
*/
app.post('/auth/login', function(req, res) {
User.findOne({ email: req.body.email }, '+password', function(err, user) {
if (!user) {
return res.status(401).send({ message: { email: 'Incorrect email' } });
}
bcrypt.compare(req.body.password, user.password, function(err, isMatch) {
if (!isMatch) {
return res.status(401).send({ message: { password: 'Incorrect password' } });
}
user = user.toObject();
delete user.password;
var token = createToken(user);
res.send({ token: token, user: user });
});
});
});
/*
|--------------------------------------------------------------------------
| Create Email and Password Account
|--------------------------------------------------------------------------
*/
app.post('/auth/signup', function(req, res) {
User.findOne({ email: req.body.email }, function(err, existingUser) {
if (existingUser) {
return res.status(409).send({ message: 'Email is already taken.' });
}
var user = new User({
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
user.password = hash;
user.save(function() {
var token = createToken(user);
res.send({ token: token, user: user });
});
});
});
});
});
/*
|--------------------------------------------------------------------------
| Sign in with Instagram
|--------------------------------------------------------------------------
*/
app.post('/auth/instagram', function(req, res) {
var accessTokenUrl = 'https://api.instagram.com/oauth/access_token';
var params = {
client_id: req.body.clientId,
redirect_uri: req.body.redirectUri,
client_secret: config.clientSecret,
code: req.body.code,
grant_type: 'authorization_code'
};
// Step 1. Exchange authorization code for access token.
request.post({ url: accessTokenUrl, form: params, json: true }, function(error, response, body) {
// Step 2a. Link user accounts.
if (req.headers.authorization) {
User.findOne({ instagramId: body.user.id }, function(err, existingUser) {
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, config.tokenSecret);
User.findById(payload.sub, '+password', function(err, localUser) {
if (!localUser) {
return res.status(400).send({ message: 'User not found.' });
}
// Merge two accounts. Instagram account takes precedence. Email account is deleted.
if (existingUser) {
existingUser.email = localUser.email;
existingUser.password = localUser.password;
localUser.remove();
existingUser.save(function() {
var token = createToken(existingUser);
return res.send({ token: token, user: existingUser });
});
} else {
// Link current email account with the Instagram profile information.
localUser.instagramId = body.user.id;
localUser.username = body.user.username;
localUser.fullName = body.user.full_name;
localUser.picture = body.user.profile_picture;
localUser.accessToken = body.access_token;
localUser.save(function() {
var token = createToken(localUser);
res.send({ token: token, user: localUser });
});
}
});
});
} else {
// Step 2b. Create a new user account or return an existing one.
User.findOne({ instagramId: body.user.id }, function(err, existingUser) {
if (existingUser) {
var token = createToken(existingUser);
return res.send({ token: token, user: existingUser });
}
var user = new User({
instagramId: body.user.id,
username: body.user.username,
fullName: body.user.full_name,
picture: body.user.profile_picture,
accessToken: body.access_token
});
user.save(function() {
var token = createToken(user);
res.send({ token: token, user: user });
});
});
}
});
});
app.get('/api/feed', isAuthenticated, function(req, res) {
var feedUrl = 'https://api.instagram.com/v1/users/self/feed';
var params = { access_token: req.user.accessToken };
request.get({ url: feedUrl, qs: params, json: true }, function(error, response, body) {
if (!error && response.statusCode == 200) {
res.send(body.data);
}
});
});
app.get('/api/media/:id', isAuthenticated, function(req, res) {
var mediaUrl = 'https://api.instagram.com/v1/media/' + req.params.id;
var params = { access_token: req.user.accessToken };
request.get({ url: mediaUrl, qs: params, json: true }, function(error, response, body) {
if (!error && response.statusCode == 200) {
res.send(body.data);
}
});
});
app.post('/api/like', isAuthenticated, function(req, res) {
var mediaId = req.body.mediaId;
var accessToken = { access_token: req.user.accessToken };
var likeUrl = 'https://api.instagram.com/v1/media/' + mediaId + '/likes';
request.post({ url: likeUrl, form: accessToken, json: true }, function(error, response, body) {
if (response.statusCode !== 200) {
return res.status(response.statusCode).send({
code: response.statusCode,
message: body.meta.error_message
});
}
res.status(200).end();
});
});
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
In that case, then you should catch all the routes in / to angular.
Put this code at the very last of your route definitions before error handlers.
app.get('*', function (req, res) {
res.sendFile('/path/to/angular/index.html');
});
As you are using Angular for your web app, you would want your express server to serve all the files related to the front-end so when you land on the link "http://localhost:8000/", Express would serve the related files back. This folder would include .js, .css and .html files as well as all the other resources (images, videos etc.) so you can link them in your markup. (eg link href="/logo.png").
You can serve these files using Express by telling express to use the Static Middleware.
Using the Middleware, you would tell Express to serve the contents of a specific folder as static resources. Putting your Angular App in the folder would then let Angular handle the routes.
var publicFolder = path.join(__dirname, '../client')
app.use(express.static(publicFolder);
You would register other endpoints to create an API for your web app. So express server would be able to provide data to the Angular app through those endpoints.

node.js & express - global modules & best practices for application structure

I'm building a node.js app that is a REST api using express and mongoose for my mongodb. I've got the CRUD endpoints all setup now, but I was just wondering two things.
How do I expand on this way of routes, specifically, how do I share modules between routes. I want each of my routes to go in a new file, but obviously only one database connection as you can see i've included mongoose at the top of people.js.
Do I have to write out the schema of the model 3 times in my people.js? The first schema defines the model, then I list all the vars out in the createPerson and updatePerson functions. This feels like how I made php/mysql CRUD back in the day lol. For the update function, I've tried writing a loop to loop through "p" to auto detect what fields to update, but to no avail. Any tips or suggestions would be great.
Also, I'd love any opinions on the app as a whole, being new to node, it's hard to know that the way you are doing something is the most efficient or "best" practice. Thanks!
app.js
// Node Modules
var express = require('express');
app = express();
app.port = 3000;
// Routes
var people = require('./routes/people');
/*
var locations = require('./routes/locations');
var menus = require('./routes/menus');
var products = require('./routes/products');
*/
// Node Configure
app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
});
// Start the server on port 3000
app.listen(app.port);
/*********
ENDPOINTS
*********/
// People
app.get('/people', people.allPeople); // Return all people
app.post('/people', people.createPerson); // Create A Person
app.get('/people/:id', people.personById); // Return person by id
app.put('/people/:id', people.updatePerson); // Update a person by id
app.delete('/people/:id', people.deletePerson); // Delete a person by id
console.log('Server started on port ' + app.port);
people.js
//Database
var mongoose = require("mongoose");
mongoose.connect('mongodb://Shans-MacBook-Pro.local/lantern/');
// Schema
var Schema = mongoose.Schema;
var Person = new Schema({
first_name: String,
last_name: String,
address: {
unit: Number,
address: String,
zipcode: String,
city: String,
region: String,
country: String
},
image: String,
job_title: String,
created_at: { type: Date, default: Date.now },
active_until: { type: Date, default: null },
hourly_wage: Number,
store_id: Number, // Inheirit store info
employee_number: Number
});
var PersonModel = mongoose.model('Person', Person);
// Return all people
exports.allPeople = function(req, res){
return PersonModel.find(function (err, person) {
if (!err) {
return res.send(person);
} else {
return res.send(err);
}
});
}
// Create A Person
exports.createPerson = function(req, res){
var person = new PersonModel({
first_name: req.body.first_name,
last_name: req.body.last_name,
address: {
unit: req.body.address.unit,
address: req.body.address.address,
zipcode: req.body.address.zipcode,
city: req.body.address.city,
region: req.body.address.region,
country: req.body.address.country
},
image: req.body.image,
job_title: req.body.job_title,
hourly_wage: req.body.hourly_wage,
store_id: req.body.location,
employee_number: req.body.employee_number
});
person.save(function (err) {
if (!err) {
return res.send(person);
} else {
console.log(err);
return res.send(404, { error: "Person was not created." });
}
});
return res.send(person);
}
// Return person by id
exports.personById = function (req, res){
return PersonModel.findById(req.params.id, function (err, person) {
if (!err) {
return res.send(person);
} else {
console.log(err);
return res.send(404, { error: "That person doesn't exist." });
}
});
}
// Delete a person by id
exports.deletePerson = function (req, res){
return PersonModel.findById(req.params.id, function (err, person) {
return person.remove(function (err) {
if (!err) {
return res.send(person.id + " deleted");
} else {
console.log(err);
return res.send(404, { error: "Person was not deleted." });
}
});
});
}
// Update a person by id
exports.updatePerson = function(req, res){
return PersonModel.findById(req.params.id, function(err, p){
if(!p){
return res.send(err)
} else {
p.first_name = req.body.first_name;
p.last_name = req.body.last_name;
p.address.unit = req.body.address.unit;
p.address.address = req.body.address.address;
p.address.zipcode = req.body.address.zipcode;
p.address.city = req.body.address.city;
p.address.region = req.body.address.region;
p.address.country = req.body.address.country;
p.image = req.body.image;
p.job_title = req.body.job_title;
p.hourly_wage = req.body.hourly_wage;
p.store_id = req.body.location;
p.employee_number = req.body.employee_number;
p.save(function(err){
if(!err){
return res.send(p);
} else {
console.log(err);
return res.send(404, { error: "Person was not updated." });
}
});
}
});
}
I have taken another approach here. Not saying it is the best, but let me explain.
Each schema (and model) is in its own file (module)
Each group of routes for a particular REST resource are in their own file (module)
Each route module just requires the Mongoose model it needs (only 1)
The main file (application entry point) just requires all route modules to register them.
The Mongo connection is in the root file and is passed as parameter to whatever needs it.
I have two subfolders under my app root - routes and schemas.
The benefits of this approach are:
You only write the schema once.
You do not pollute your main app file with route registrations for 4-5 routes per REST resource (CRUD)
You only define the DB connection once
Here is how a particular schema file looks:
File: /schemas/theaterSchema.js
module.exports = function(db) {
return db.model('Theater', TheaterSchema());
}
function TheaterSchema () {
var Schema = require('mongoose').Schema;
return new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
address: { type: String, required: true },
latitude: { type: Number, required: false },
longitude: { type: Number, required: false },
phone: { type: String, required: false }
});
}
Here is how a collection of routes for a particular resource looks:
File: /routes/theaters.js
module.exports = function (app, options) {
var mongoose = options.mongoose;
var Schema = options.mongoose.Schema;
var db = options.db;
var TheaterModel = require('../schemas/theaterSchema')(db);
app.get('/api/theaters', function (req, res) {
var qSkip = req.query.skip;
var qTake = req.query.take;
var qSort = req.query.sort;
var qFilter = req.query.filter;
return TheaterModel.find().sort(qSort).skip(qSkip).limit(qTake)
.exec(function (err, theaters) {
// more code
});
});
app.post('/api/theaters', function (req, res) {
var theater;
theater.save(function (err) {
// more code
});
return res.send(theater);
});
app.get('/api/theaters/:id', function (req, res) {
return TheaterModel.findById(req.params.id, function (err, theater) {
// more code
});
});
app.put('/api/theaters/:id', function (req, res) {
return TheaterModel.findById(req.params.id, function (err, theater) {
// more code
});
});
app.delete('/api/theaters/:id', function (req, res) {
return TheaterModel.findById(req.params.id, function (err, theater) {
return theater.remove(function (err) {
// more code
});
});
});
};
And here is the root application file, which initialized the connection and registers all routes:
File: app.js
var application_root = __dirname,
express = require('express'),
path = require('path'),
mongoose = require('mongoose'),
http = require('http');
var app = express();
var dbProduction = mongoose.createConnection('mongodb://here_insert_the_mongo_connection_string');
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use('/images/tmb', express.static(path.join(application_root, "images/tmb")));
app.use('/images/plays', express.static(path.join(application_root, "images/plays")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.get('/api', function (req, res) {
res.send('API is running');
});
var theatersApi = require('./routes/theaters')(app, { 'mongoose': mongoose, 'db': dbProduction });
// more code
app.listen(4242);
Hope this was helpful.
I found this StackOverflow post very helpful:
File Structure of Mongoose & NodeJS Project
The trick is to put your schema into models directory. Then, in any route, you can require('../models').whatever.
Also, I generally start the mongoose db connection in app.js, and only start the Express server once the connection is up:
mongoose.connect('mongodb://localhost/whateverdb')
mongoose.connection.on('error', function(err) {
console.log("Error while connecting to MongoDB: " + err);
process.exit();
});
mongoose.connection.on('connected', function(err) {
console.log('mongoose is now connected');
// start app here
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
});
I'd take a look at this project https://github.com/madhums/node-express-mongoose-demo . It is a great example on how to build a nodejs application in a standard way.

Categories

Resources