We are going to create a photo sharing service where the user is able to upload pictures and like them.
We will be using a simple MVC, so our file structure will be:
/controllers
/users.js
/photos.js
/likes.js
/models
/users.js # this will be half-mocked up since there's no time
# or we'll use auth0 if possible
/views
/index.pug
/login.pug
/photo.pug
/.env
/.gitignore
/app.js
/package.json
/routes.js
The user will be able to login (actually no, we will fake this)
For this, first we set up our app.js:
require('dotenv').config();
var express = require('express');
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.once('open', function(){
var app = express();
app.set('view engine', 'pug');
app.use(express.static('public'));
app.use(bodyparser.urlencoded({ extended: false }));
app.use(require('./routes'));
app.listen(process.env.PORT || 3000);
});
In routes.js:
var express = require('express');
var router = express.Router();
var controllers = require('auto-load')('controllers');
router.get('/', controllers.photos.index);
module.exports = router;
Then in our controllers/photos.js:
var formidable = require('formidable');
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: process.env.cloud,
api_key: process.env.key,
api_secret: process.env.secret
});
exports.upload = function(req, res, next){
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
if (err) next(err);
cloudinary.uploader.upload(files.image.path, function(result) {
// Let's force https in the image:
var image = result.url.replace('http://', 'https://');
res.json({ error: false, image: image });
});
});
});
Our layout.pug:
doctype html
html
head
title= title
link(rel="stylesheet" href="https://cdn.jsdelivr.net/picnicss/6.0.0/plugins.min.css")
link(rel='stylesheet', href='style.css')
body
block content
In photos.pug:
extends layout
block content
each photo in photos
img(src=photo)
button.like
Auth
We will follow Auth0 tutorial.