generated from dwd/saveToMongo
54 lines
1.2 KiB
JavaScript
54 lines
1.2 KiB
JavaScript
const express = require('express');
|
|
const dotenv = require('dotenv');
|
|
// const jwt = require('jsonwebtoken');
|
|
// const fs = require('fs');
|
|
const cors = require('cors');
|
|
const app = express();
|
|
let corsOptions = fs.readFileSync('origin.cors');
|
|
app.use(cors(corsOptions));
|
|
dotenv.config();
|
|
let port = process.env.PORT || 5000;
|
|
|
|
mongoose.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true, useUnifiedTopology: true });
|
|
|
|
const PostSchema = new mongoose.Schema({
|
|
title: String,
|
|
body: String,
|
|
});
|
|
|
|
const Post = mongoose.model("Post", PostSchema);
|
|
|
|
app.get("/posts", async (req, res) => {
|
|
const posts = await Post.find();
|
|
res.json(posts);
|
|
});
|
|
|
|
app.post("/posts", async (req, res) => {
|
|
const post = new Post({
|
|
title: req.body.title,
|
|
body: req.body.body,
|
|
});
|
|
|
|
await post.save();
|
|
|
|
res.json(post);
|
|
});
|
|
|
|
app.put("/posts/:id", async (req, res) => {
|
|
const post = await Post.findByIdAndUpdate(req.params.id, req.body);
|
|
|
|
res.json(post);
|
|
});
|
|
|
|
app.delete("/posts/:id", async (req, res) => {
|
|
await Post.findByIdAndRemove(req.params.id);
|
|
|
|
res.json({ message: "Post deleted successfully" });
|
|
});
|
|
|
|
|
|
app.listen(port, () => {
|
|
console.log(`FileAccessJWT API listening on port ${port}`)
|
|
})
|
|
|