Skip to content

Instantly share code, notes, and snippets.

View donjosef's full-sized avatar

Giuseppe Montanaro donjosef

View GitHub Profile
@donjosef
donjosef / app.js
Last active September 26, 2019 15:37
Connect to database
const mongoose = require('mongoose');
//connect our server to database created with atlas
//Be sure to type this at the very bottom of the file, AFTER all the app.use()
mongoose
.connect('mongodb+srv://giuseppe:<password>@cluster0-rchmx.mongodb.net/test?retryWrites=true&w=majority')
.then(() => {
app.listen(8080, () => {
console.log('Server listening on port 8080...')
})
@donjosef
donjosef / posts.js
Last active September 24, 2019 19:15
Create controllers/middlewares
const Post = require('../model.js'); //Our Model
module.exports = {
getPosts: (req, res, next) => {
//Find posts in posts collection
Post.find()
.then(posts => {
res.status(200).json({ message: 'Posts fetched!', posts })
})
@donjosef
donjosef / model.js
Created September 24, 2019 19:09
Create our Post monogoose model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema({
title: {
type: String,
required: true
},
content: {
@donjosef
donjosef / app.js
Created September 24, 2019 18:28
Plug router into app to start handling routing
const postsRoutes = require('./routes/posts');
app.use(postsRoutes); //before mongoose.connect()
@donjosef
donjosef / posts.js
Created September 24, 2019 18:21
Define routes for handling requests
const express = require('express');
const controller = require('../controllers/posts');
const router = express.Router(); //router is like a mini express app, that we can plug into app.use()
//With this we are determining how our application will respond to get requests to /posts
router.get('/posts', controller.getPosts);
//With this we are determining how our application will respond to post requests to /post
@donjosef
donjosef / app.js
Created September 24, 2019 17:15
Initialize settings for express
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
//middleware to allow the parsing of the incoming request body
app.use(bodyParser.json());
//Middleware to set response headers to handle CORS errors
app.use((req, res, next) => {