Skip to content

Instantly share code, notes, and snippets.

@skd1993
Created June 9, 2021 10:01
Show Gist options
  • Save skd1993/1f6f046cca7c2a9143849c64eaa7fa6d to your computer and use it in GitHub Desktop.
Save skd1993/1f6f046cca7c2a9143849c64eaa7fa6d to your computer and use it in GitHub Desktop.
Basic NodeJS API starter
const http = require('http')
const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
const blogSchema = new mongoose.Schema({
title: String,
author: String,
url: String,
likes: Number
})
const Blog = mongoose.model('Blog', blogSchema)
const mongoUrl = 'mongodb://localhost/bloglist'
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true })
app.use(cors())
app.use(express.json())
app.get('/api/blogs', (request, response) => {
Blog
.find({})
.then(blogs => {
response.json(blogs)
})
})
app.post('/api/blogs', (request, response) => {
const blog = new Blog(request.body)
blog
.save()
.then(result => {
response.status(201).json(result)
})
})
const PORT = 3003
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment