Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Created July 4, 2020 11:50
Show Gist options
  • Select an option

  • Save heytulsiprasad/e1be4fff1d1b44d6028760c119de8b88 to your computer and use it in GitHub Desktop.

Select an option

Save heytulsiprasad/e1be4fff1d1b44d6028760c119de8b88 to your computer and use it in GitHub Desktop.
A demo express backend made for CRUD centric applications
const express = require("express")
const router = express.Router();
const Todo = require("../models/todo")
router.get("/todos", (req, res, next) => {
Todo.find({}, "action")
.then(data => res.json(data))
.catch(next);
})
router.post("/todos", (req, res, next) => {
if (req.body.action) {
Todo.create(req.body)
.then(data => res.json(data))
.catch(next)
} else {
res.json({
error: "The input field is empty!"
})
}
})
router.delete("/todos/:id", (req, res, next) => {
Todo.findOneAndDelete({ "_id": req.params.id})
.then(data => res.json(data))
.catch(next)
})
module.exports = router;
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// create a schema
const TodoSchema = new Schema({
action: {
type: String,
required: [true, "The todo text field is required"],
},
});
// create a model
const Todo = mongoose.model("todo", TodoSchema);
module.exports = Todo;
const express = require("express");
require("dotenv").config();
const mongoose = require("mongoose");
const routes = require("./routes/api");
mongoose
.connect(process.env.DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("Database is connected successfully"))
.catch((err) => console.log(err));
// mongoose promise is deprecated, we override it with node's promise
mongoose.Promise = global.Promise;
const port = process.env.PORT || 5000;
const app = express();
app.use((req, res, next) => {
res.header("Allow-Access-Allow-Origin", "*");
res.header(
"Allow-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use(express.json());
app.use("/api", routes);
app.use((err, req, res, next) => {
console.log(err);
next();
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
@heytulsiprasad

Copy link
Copy Markdown
Author

This is how we set a header in responses back to the client side javascript:

app.use((req, res, next) => {
	res.header("Allow-Access-Allow-Origin", "*");
	res.header(
		"Allow-Control-Allow-Headers",
		"Origin, X-Requested-With, Content-Type, Accept"
	);
	next();
});

And this is how we handle the error messages (if occurred any) in the backend, using middlewares:

app.use((err, req, res, next) => {
	console.log(err);
	next();
});

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