n
nIn part 1 we created the client app (Ionic 2 App), in this part we will focus on building the NodeJS API.
n
nI assume that you are familiar with creating NodeJS App as am not going to go into details about how to create a NodeJS API.
n
nThe NodeJS API will be deployed to Heroku. The images will be uploaded to Cloudinary server, and the MongoDB hosted in MLab.
n
n
nnnn
n
nAm not going to go into details about Heroku, Cloudinary, and MLab, you can read more about them in their respective websites.
n
n
nProject Structure and Dependencies
nSince our API is written with NodeJS, the first thing is to create our project directory and add package.json where will add all our API dependencies.
n
nThe package.json should look like so:
n
n
{n "name": "photocloud",n "version": "1.0.0",n "description": "A nodejs app to upload image to cloudinary",n "main": "app.js",n "scripts": {n "start": "node app.js"n },n "keywords": [n "cloudinary",n "nodejs",n "api",n "heroku",n "mongodb",n "photo-upload"n ],n "author": "Mark Adesina",n "license": "MIT",n "dependencies": {n "body-parser": "^1.15.2",n "cloudinary": "^1.4.4",n "connect-multiparty": "^2.0.0",n "cors": "^2.8.1",n "express": "^4.14.0",n "mongoose": "^4.6.6"n },n "engines": {n "node": "6.0.0"n }n}nnn
n
nThere is nothing too complex about the package.json file. But our main concern here is the dependencies. The dependencies we will require for this API are:
n
- n
- Cloudinary
- Body-Parser
- Connect-Multiparty
- Cors
- Express
- Mongoose
n
n
n
n
n
n
n
n
n
n
n
n
npm installn
n
n
n
nTo have an overview of the project, it is always a good idea to present a directory structure of the app:
n
n
n
n
nNow, we will setup our server. Open the file named app.js located in the root of server folder and paste the code below. This is the entry point into our node application.
n
n
n
var express = require('express'),n app = express(),n bodyParser = require('body-parser'),n cors = require('cors'),n config = require('./config/settings'),n db = require('./db/db');n server = require('http').createServer(app); nnnapp.set('port', (process.env.PORT || config.serverPort));nnapp.use(bodyParser.urlencoded({ extended: true }));napp.use(bodyParser.json());napp.use(cors());nnrequire('./route/route')(express,app);nnnserver.listen(app.get('port'), function() {n console.log('Node app is running on port', app.get('port'));n});nn
nThis tutorial is not aimed at teaching NodeJS application, so I wont explain some of the content of the files that we have here. The source code will be available on my github page.
n
n
nAccessing Cloudinary API SDKs
nCreate a free account on cloudinary website.
n
nThe dashboard shows a list of SDKs that you can use to talk to Cloudinary in most of the popular languages including Node.js.
n
nCloudinary core exposes APIs based on your cloud name and all these SDKs do is serve as a language wrapper to these URL. So instead of littering your app with these URLs, you have a better intuitive language based method APIs to work with.
n
nThe cloud name is not your name but the name you chose when signing up as cloud name. There three things you need to take note of in your dashboard they are your Cloud Name, API Key, and API Secret.
n
n
nHandling Image Upload
nWe will cover how you can upload your images to cloudinary server. First update the settings.js located in the config folder of your NodeJS App like so:
n
n
module.exports = {n 'serverPort':5000,n 'dbUrl':'mongodb://dbuser:dbpassword@ds143737.mlab.com:43737/dbname',n 'cloud_name': 'YOUR_CLOUD_NAME',n 'api_key': 'YOUR_API_KEY',n 'api_secret': 'YOUR_API_KEY_SECRET'nn}nn
nReplace the dbUrl to reflect your MongoDb url as found in MLab when you created yours, your cloud_name, api_key and api_secret should also reflect yours as found in yourncloudinary server Dashboard.nnnnnnSo let’s see how we can upload images to the cloud using the cloudinary NodeJS SDK we have installed. Paste the code below in post.js located in controller folder in the nodejs app.nnn/controller/post.jsnn
n
var Post = require('../models/post');nvar config = require('../config/settings'),n cloudinary = require('cloudinary');nvar multipart = require('connect-multiparty')();nncloudinary.config({n cloud_name: config.cloud_name,n api_key: config.api_key,n api_secret: config.api_secretn});nnmodule.exports = {nn upload: function (req, res, next) {n n cloudinary.uploader.upload(req.files.file.path, function (resp) {nn var newPost = new Post({n title: req.body.title,n image_url: resp.url,n description: req.body.descriptionn }).save(function (err, response) {n if (err) return next(err);n res.json({n error: false,n result: responsen });n })nn });nn },n get: function (req, res, next) {n Post.find({}, function (err, result) {n if(err) return next(err);n res.json({posts:result});n });n }nn}nn
n
n
n
let options = {n fileKey: "file",n fileName: filename,n chunkedMode: false,n mimeType: "image/jpg",n params: { 'title': this.postTitle, 'description': this.desc }n };n
n
nYou can see that the fileKey value is file, that is why we now have the file keyword to access the incoming file within our NodeJS App.n
n
nDeployment App to Heroku
n
nYou can read this article on how to deploy the app to heroku server.
n
nThe full source code can found here.
n
nYour comments are welcome. Happy Coding.
n
