Skip to content

Instantly share code, notes, and snippets.

Giuseppe Montanaro donjosef

Block or report user

Report or block donjosef

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
@donjosef
donjosef / model.js
Created Sep 24, 2019
Create our Post monogoose model
View model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema({
title: {
type: String,
required: true
},
content: {
@donjosef
donjosef / posts.js
Last active Sep 24, 2019
Create controllers/middlewares
View posts.js
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 / app.js
Created Sep 24, 2019
Plug router into app to start handling routing
View app.js
const postsRoutes = require('./routes/posts');
app.use(postsRoutes); //before mongoose.connect()
@donjosef
donjosef / posts.js
Created Sep 24, 2019
Define routes for handling requests
View posts.js
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
Last active Sep 26, 2019
Connect to database
View app.js
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 / app.js
Created Sep 24, 2019
Initialize settings for express
View app.js
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) => {
You can’t perform that action at this time.