Skip to content

Instantly share code, notes, and snippets.

@guarmo
Created December 4, 2020 15:42
Show Gist options
  • Save guarmo/2979e8513c6334a35c3c8912e627a577 to your computer and use it in GitHub Desktop.
Save guarmo/2979e8513c6334a35c3c8912e627a577 to your computer and use it in GitHub Desktop.

Create RESTful API

Start

Create package.json

npm init -y

Install express and nodemon

npm install express nodemon 

In package.json under scripts add: “start”: “nodemo app.js”

Create app.js

touch app.js

Import, use express and listen on port 3000

Connect to database

Install Mongoose

npm install mongoose

Create cluster on mongodb

Install dotenv

npm install dotenv

Create .env file, store mongoose url in .env global variable

Import and connect mongoose (process.env.VARIABLENAME)

Create routes

Create routes folder

Create new file posts.js in routes folder

Import express

const router = express.Router();
router.get('/', (req, res) => {
  // do something here
})

Export routes

module.exports = router;

In app.js import routes and add middleware:

const postRoute = require(‘./routes/posts’);
app.use(‘/posts’, postRoutes)

Create model

Create models folder

Create Post.js file

Import mongoose

const mongoose = require("mongoose");

Create schema

const PostSchema = mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  }
  )}

Export the schema

module.exports = mongoose.model(‘Posts’, PostSchema);

Install Cors

npm install cors

Import & use Cors

const cors = require('cors');
app.use(cors())

In app.js: add bodyparser

const bodyParser = require('body-parser');
app.use(bodyParser.json());

In posts.js import model

const Post = require(‘../models/Post’);

Create routes (get, post, patch, update);

router.get("/", async (req, res) => {
  try {
    const posts = await Post.find();
    res.json(posts);
  } catch (err) {
    res.json({ message: err });
  }
});


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment