Express.js: REST Api
npm init
npm install --save express
npm install --save-dev nodemon //for re-running app automatically
npm install --save body-parser //for parsing requests
We can test this for example through Insomnia
to test POST
and GET
.
GET locahost:8080/feed/posts
POST locahost:8080/feed/posts
//Example JSON data:
{
"title": "Test title",
"content": "Test Content"
}
Or we can test this on codepen.com
:
const getButton = document.getElementById('get');
const postButton = document.getElementById('post');
getButton.addEventListener('click',() => {
fetch('http://localhost:8080/feed/posts')
.then(res => res.json())
.then(resData => console.log(resData))
.catch(err => console.log(err));
});
postButton.addEventListener('click',() => {
fetch('http://localhost:8080/feed/post',
{
method: 'POST',
body: JSON.stringify({
title: 'test post from codepen',
body: 'body from codepen'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(resData => console.log(resData))
.catch(err => console.log(err));
});
.gitignore
node_modules
package.json
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app.js"
},
...
controllers/feed.js
exports.getPosts = (req, res, next) => {
res.status(200).json({
posts: [{ title: 'First Post', content: 'This is the first post' }]
});
};
exports.createPost = (req, res, next) => {
const title = req.body.title;
const content = req.body.content;
//Create post in db
res.status(201).json({
message: 'Post created successfully',
post: { id: new Date().toISOString(), title: title, content:content }
})
}
routes/feed.js
const express = require('express');
const feedController = require('../controllers/feed');
const router = express.Router();
//GET /feed/posts
router.get('/posts', feedController.getPosts);
//POST /feed/post
router.post('/post', feedController.createPost);
module.exports = router;
app.js
const express = require('express');
const feedRoutes = require('./routes/feed');
const bodyParser = require('body-parser');
const app = express();
// app.use(bodyParser.urlencoded()); //for x-www-form-urlencoded, sending requests via form
app.use(bodyParser.json()); // application/json
// we need to set headers to avoid CORS issues
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
})
app.use('/feed',feedRoutes);
app.listen(8080);