Created
June 9, 2021 10:01
-
-
Save skd1993/1f6f046cca7c2a9143849c64eaa7fa6d to your computer and use it in GitHub Desktop.
Basic NodeJS API starter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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